repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/win_smtp_server.py
|
get_connection_ip_list
|
python
|
def get_connection_ip_list(as_wmi_format=False, server=_DEFAULT_SERVER):
'''
Get the IPGrant list for the SMTP virtual server.
:param bool as_wmi_format: Returns the connection IPs as a list in the format WMI expects.
:param str server: The SMTP server name.
:return: A dictionary of the IP and subnet pairs.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_connection_ip_list
'''
ret = dict()
setting = 'IPGrant'
reg_separator = r',\s*'
if as_wmi_format:
ret = list()
addresses = _get_wmi_setting('IIsIPSecuritySetting', setting, server)
# WMI returns the addresses as a tuple of unicode strings, each representing
# an address/subnet pair. Remove extra spaces that may be present.
for unnormalized_address in addresses:
ip_address, subnet = re.split(reg_separator, unnormalized_address)
if as_wmi_format:
ret.append('{0}, {1}'.format(ip_address, subnet))
else:
ret[ip_address] = subnet
if not ret:
_LOG.debug('%s is empty.', setting)
return ret
|
Get the IPGrant list for the SMTP virtual server.
:param bool as_wmi_format: Returns the connection IPs as a list in the format WMI expects.
:param str server: The SMTP server name.
:return: A dictionary of the IP and subnet pairs.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_connection_ip_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_smtp_server.py#L364-L400
|
[
"def _get_wmi_setting(wmi_class_name, setting, server):\n '''\n Get the value of the setting for the provided class.\n '''\n with salt.utils.winapi.Com():\n try:\n connection = wmi.WMI(namespace=_WMI_NAMESPACE)\n wmi_class = getattr(connection, wmi_class_name)\n\n objs = wmi_class([setting], Name=server)[0]\n ret = getattr(objs, setting)\n except wmi.x_wmi as error:\n _LOG.error('Encountered WMI error: %s', error.com_error)\n except (AttributeError, IndexError) as error:\n _LOG.error('Error getting %s: %s', wmi_class_name, error)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing IIS SMTP server configuration on Windows servers.
The Windows features 'SMTP-Server' and 'Web-WMI' must be installed.
:depends: wmi
'''
# IIS metabase configuration settings:
# https://goo.gl/XCt1uO
# IIS logging options:
# https://goo.gl/RL8ki9
# https://goo.gl/iwnDow
# MicrosoftIISv2 namespace in Windows 2008r2 and later:
# http://goo.gl/O4m48T
# Connection and relay IPs in PowerShell:
# https://goo.gl/aBMZ9K
# http://goo.gl/MrybFq
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
# Import Salt libs
from salt.exceptions import SaltInvocationError
import salt.utils.args
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import wmi
import salt.utils.winapi
_HAS_MODULE_DEPENDENCIES = True
except ImportError:
_HAS_MODULE_DEPENDENCIES = False
_DEFAULT_SERVER = 'SmtpSvc/1'
_WMI_NAMESPACE = 'MicrosoftIISv2'
_LOG = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'win_smtp_server'
def __virtual__():
'''
Only works on Windows systems.
'''
if salt.utils.platform.is_windows() and _HAS_MODULE_DEPENDENCIES:
return __virtualname__
return False
def _get_wmi_setting(wmi_class_name, setting, server):
'''
Get the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class([setting], Name=server)[0]
ret = getattr(objs, setting)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
return ret
def _set_wmi_setting(wmi_class_name, setting, value, server):
'''
Set the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class(Name=server)[0]
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
try:
setattr(objs, setting, value)
return True
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except AttributeError as error:
_LOG.error('Error setting %s: %s', setting, error)
return False
def _normalize_server_settings(**settings):
'''
Convert setting values that had been improperly converted to a dict back to a string.
'''
ret = dict()
settings = salt.utils.args.clean_kwargs(**settings)
for setting in settings:
if isinstance(settings[setting], dict):
_LOG.debug('Fixing value: %s', settings[setting])
value_from_key = next(six.iterkeys(settings[setting]))
ret[setting] = "{{{0}}}".format(value_from_key)
else:
ret[setting] = settings[setting]
return ret
def get_log_format_types():
'''
Get all available log format names and ids.
:return: A dictionary of the log format names and ids.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_log_format_types
'''
ret = dict()
prefix = 'logging/'
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IISLogModuleSetting()
# Remove the prefix from the name.
for obj in objs:
name = six.text_type(obj.Name).replace(prefix, '', 1)
ret[name] = six.text_type(obj.LogModuleId)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IISLogModuleSetting: %s', error)
if not ret:
_LOG.error('Unable to get log format types.')
return ret
def get_servers():
'''
Get the SMTP virtual server names.
:return: A list of the SMTP virtual servers.
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_servers
'''
ret = list()
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting()
for obj in objs:
ret.append(six.text_type(obj.Name))
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
_LOG.debug('Found SMTP servers: %s', ret)
return ret
def get_server_setting(settings, server=_DEFAULT_SERVER):
'''
Get the value of the setting for the SMTP virtual server.
:param str settings: A list of the setting names.
:param str server: The SMTP server name.
:return: A dictionary of the provided settings and their values.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_server_setting settings="['MaxRecipients']"
'''
ret = dict()
if not settings:
_LOG.warning('No settings provided.')
return ret
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting(settings, Name=server)[0]
for setting in settings:
ret[setting] = six.text_type(getattr(objs, setting))
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
return ret
def set_server_setting(settings, server=_DEFAULT_SERVER):
'''
Set the value of the setting for the SMTP virtual server.
.. note::
The setting names are case-sensitive.
:param str settings: A dictionary of the setting names and their values.
:param str server: The SMTP server name.
:return: A boolean representing whether all changes succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_server_setting settings="{'MaxRecipients': '500'}"
'''
if not settings:
_LOG.warning('No settings provided')
return False
# Some fields are formatted like '{data}'. Salt tries to convert these to dicts
# automatically on input, so convert them back to the proper format.
settings = _normalize_server_settings(**settings)
current_settings = get_server_setting(settings=settings.keys(), server=server)
if settings == current_settings:
_LOG.debug('Settings already contain the provided values.')
return True
# Note that we must fetch all properties of IIsSmtpServerSetting below, since
# filtering for specific properties and then attempting to set them will cause
# an error like: wmi.x_wmi Unexpected COM Error -2147352567
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting(Name=server)[0]
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(current_settings[setting]):
try:
setattr(objs, setting, settings[setting])
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except AttributeError as error:
_LOG.error('Error setting %s: %s', setting, error)
# Get the settings post-change so that we can verify tht all properties
# were modified successfully. Track the ones that weren't.
new_settings = get_server_setting(settings=settings.keys(), server=server)
failed_settings = dict()
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(new_settings[setting]):
failed_settings[setting] = settings[setting]
if failed_settings:
_LOG.error('Failed to change settings: %s', failed_settings)
return False
_LOG.debug('Settings configured successfully: %s', settings.keys())
return True
def get_log_format(server=_DEFAULT_SERVER):
'''
Get the active log format for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A string of the log format name.
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_log_format
'''
log_format_types = get_log_format_types()
format_id = _get_wmi_setting('IIsSmtpServerSetting', 'LogPluginClsid', server)
# Since IIsSmtpServerSetting stores the log type as an id, we need
# to get the mapping from IISLogModuleSetting and extract the name.
for key in log_format_types:
if six.text_type(format_id) == log_format_types[key]:
return key
_LOG.warning('Unable to determine log format.')
return None
def set_log_format(log_format, server=_DEFAULT_SERVER):
'''
Set the active log format for the SMTP virtual server.
:param str log_format: The log format name.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_log_format 'Microsoft IIS Log File Format'
'''
setting = 'LogPluginClsid'
log_format_types = get_log_format_types()
format_id = log_format_types.get(log_format, None)
if not format_id:
message = ("Invalid log format '{0}' specified. Valid formats:"
' {1}').format(log_format, log_format_types.keys())
raise SaltInvocationError(message)
_LOG.debug("Id for '%s' found: %s", log_format, format_id)
current_log_format = get_log_format(server)
if log_format == current_log_format:
_LOG.debug('%s already contains the provided format.', setting)
return True
_set_wmi_setting('IIsSmtpServerSetting', setting, format_id, server)
new_log_format = get_log_format(server)
ret = log_format == new_log_format
if ret:
_LOG.debug("Setting %s configured successfully: %s", setting, log_format)
else:
_LOG.error("Unable to configure %s with value: %s", setting, log_format)
return ret
def set_connection_ip_list(addresses=None, grant_by_default=False, server=_DEFAULT_SERVER):
'''
Set the IPGrant list for the SMTP virtual server.
:param str addresses: A dictionary of IP + subnet pairs.
:param bool grant_by_default: Whether the addresses should be a blacklist or whitelist.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_connection_ip_list addresses="{'127.0.0.1': '255.255.255.255'}"
'''
setting = 'IPGrant'
formatted_addresses = list()
# It's okay to accept an empty list for set_connection_ip_list,
# since an empty list may be desirable.
if not addresses:
addresses = dict()
_LOG.debug('Empty %s specified.', setting)
# Convert addresses to the 'ip_address, subnet' format used by
# IIsIPSecuritySetting.
for address in addresses:
formatted_addresses.append('{0}, {1}'.format(address.strip(),
addresses[address].strip()))
current_addresses = get_connection_ip_list(as_wmi_format=True, server=server)
# Order is not important, so compare to the current addresses as unordered sets.
if set(formatted_addresses) == set(current_addresses):
_LOG.debug('%s already contains the provided addresses.', setting)
return True
# First we should check GrantByDefault, and change it if necessary.
current_grant_by_default = _get_wmi_setting('IIsIPSecuritySetting', 'GrantByDefault', server)
if grant_by_default != current_grant_by_default:
_LOG.debug('Setting GrantByDefault to: %s', grant_by_default)
_set_wmi_setting('IIsIPSecuritySetting', 'GrantByDefault', grant_by_default, server)
_set_wmi_setting('IIsIPSecuritySetting', setting, formatted_addresses, server)
new_addresses = get_connection_ip_list(as_wmi_format=True, server=server)
ret = set(formatted_addresses) == set(new_addresses)
if ret:
_LOG.debug('%s configured successfully: %s', setting, formatted_addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, formatted_addresses)
return ret
def get_relay_ip_list(server=_DEFAULT_SERVER):
'''
Get the RelayIpList list for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A list of the relay IPs.
:rtype: list
.. note::
A return value of None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list, and setting an empty list/tuple corresponds to the more
permissive 'All except the list below' GUI parameter.
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_relay_ip_list
'''
ret = list()
setting = 'RelayIpList'
lines = _get_wmi_setting('IIsSmtpServerSetting', setting, server)
if not lines:
_LOG.debug('%s is empty: %s', setting, lines)
if lines is None:
lines = [None]
return list(lines)
# WMI returns the addresses as a tuple of individual octets, so we
# need to group them and reassemble them into IP addresses.
i = 0
while i < len(lines):
octets = [six.text_type(x) for x in lines[i: i + 4]]
address = '.'.join(octets)
ret.append(address)
i += 4
return ret
def set_relay_ip_list(addresses=None, server=_DEFAULT_SERVER):
'''
Set the RelayIpList list for the SMTP virtual server.
Due to the unusual way that Windows stores the relay IPs, it is advisable to retrieve
the existing list you wish to set from a pre-configured server.
For example, setting '127.0.0.1' as an allowed relay IP through the GUI would generate
an actual relay IP list similar to the following:
.. code-block:: cfg
['24.0.0.128', '32.0.0.128', '60.0.0.128', '68.0.0.128', '1.0.0.0', '76.0.0.0',
'0.0.0.0', '0.0.0.0', '1.0.0.0', '1.0.0.0', '2.0.0.0', '2.0.0.0', '4.0.0.0',
'0.0.0.0', '76.0.0.128', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0',
'255.255.255.255', '127.0.0.1']
.. note::
Setting the list to None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list configured, and setting an empty list/tuple corresponds to the
more permissive 'All except the list below' GUI parameter.
:param str addresses: A list of the relay IPs. The order of the list is important.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_relay_ip_list addresses="['192.168.1.1', '172.16.1.1']"
'''
setting = 'RelayIpList'
formatted_addresses = list()
current_addresses = get_relay_ip_list(server)
if list(addresses) == current_addresses:
_LOG.debug('%s already contains the provided addresses.', setting)
return True
if addresses:
# The WMI input data needs to be in the format used by RelayIpList. Order
# is also important due to the way RelayIpList orders the address list.
if addresses[0] is None:
formatted_addresses = None
else:
for address in addresses:
for octet in address.split('.'):
formatted_addresses.append(octet)
_LOG.debug('Formatted %s addresses: %s', setting, formatted_addresses)
_set_wmi_setting('IIsSmtpServerSetting', setting, formatted_addresses, server)
new_addresses = get_relay_ip_list(server)
ret = list(addresses) == new_addresses
if ret:
_LOG.debug('%s configured successfully: %s', setting, addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, addresses)
return ret
|
saltstack/salt
|
salt/modules/win_smtp_server.py
|
set_connection_ip_list
|
python
|
def set_connection_ip_list(addresses=None, grant_by_default=False, server=_DEFAULT_SERVER):
'''
Set the IPGrant list for the SMTP virtual server.
:param str addresses: A dictionary of IP + subnet pairs.
:param bool grant_by_default: Whether the addresses should be a blacklist or whitelist.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_connection_ip_list addresses="{'127.0.0.1': '255.255.255.255'}"
'''
setting = 'IPGrant'
formatted_addresses = list()
# It's okay to accept an empty list for set_connection_ip_list,
# since an empty list may be desirable.
if not addresses:
addresses = dict()
_LOG.debug('Empty %s specified.', setting)
# Convert addresses to the 'ip_address, subnet' format used by
# IIsIPSecuritySetting.
for address in addresses:
formatted_addresses.append('{0}, {1}'.format(address.strip(),
addresses[address].strip()))
current_addresses = get_connection_ip_list(as_wmi_format=True, server=server)
# Order is not important, so compare to the current addresses as unordered sets.
if set(formatted_addresses) == set(current_addresses):
_LOG.debug('%s already contains the provided addresses.', setting)
return True
# First we should check GrantByDefault, and change it if necessary.
current_grant_by_default = _get_wmi_setting('IIsIPSecuritySetting', 'GrantByDefault', server)
if grant_by_default != current_grant_by_default:
_LOG.debug('Setting GrantByDefault to: %s', grant_by_default)
_set_wmi_setting('IIsIPSecuritySetting', 'GrantByDefault', grant_by_default, server)
_set_wmi_setting('IIsIPSecuritySetting', setting, formatted_addresses, server)
new_addresses = get_connection_ip_list(as_wmi_format=True, server=server)
ret = set(formatted_addresses) == set(new_addresses)
if ret:
_LOG.debug('%s configured successfully: %s', setting, formatted_addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, formatted_addresses)
return ret
|
Set the IPGrant list for the SMTP virtual server.
:param str addresses: A dictionary of IP + subnet pairs.
:param bool grant_by_default: Whether the addresses should be a blacklist or whitelist.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_connection_ip_list addresses="{'127.0.0.1': '255.255.255.255'}"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_smtp_server.py#L403-L458
|
[
"def _get_wmi_setting(wmi_class_name, setting, server):\n '''\n Get the value of the setting for the provided class.\n '''\n with salt.utils.winapi.Com():\n try:\n connection = wmi.WMI(namespace=_WMI_NAMESPACE)\n wmi_class = getattr(connection, wmi_class_name)\n\n objs = wmi_class([setting], Name=server)[0]\n ret = getattr(objs, setting)\n except wmi.x_wmi as error:\n _LOG.error('Encountered WMI error: %s', error.com_error)\n except (AttributeError, IndexError) as error:\n _LOG.error('Error getting %s: %s', wmi_class_name, error)\n return ret\n",
"def _set_wmi_setting(wmi_class_name, setting, value, server):\n '''\n Set the value of the setting for the provided class.\n '''\n with salt.utils.winapi.Com():\n try:\n connection = wmi.WMI(namespace=_WMI_NAMESPACE)\n wmi_class = getattr(connection, wmi_class_name)\n\n objs = wmi_class(Name=server)[0]\n except wmi.x_wmi as error:\n _LOG.error('Encountered WMI error: %s', error.com_error)\n except (AttributeError, IndexError) as error:\n _LOG.error('Error getting %s: %s', wmi_class_name, error)\n\n try:\n setattr(objs, setting, value)\n return True\n except wmi.x_wmi as error:\n _LOG.error('Encountered WMI error: %s', error.com_error)\n except AttributeError as error:\n _LOG.error('Error setting %s: %s', setting, error)\n return False\n",
"def get_connection_ip_list(as_wmi_format=False, server=_DEFAULT_SERVER):\n '''\n Get the IPGrant list for the SMTP virtual server.\n\n :param bool as_wmi_format: Returns the connection IPs as a list in the format WMI expects.\n :param str server: The SMTP server name.\n\n :return: A dictionary of the IP and subnet pairs.\n :rtype: dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_smtp_server.get_connection_ip_list\n '''\n ret = dict()\n setting = 'IPGrant'\n reg_separator = r',\\s*'\n\n if as_wmi_format:\n ret = list()\n\n addresses = _get_wmi_setting('IIsIPSecuritySetting', setting, server)\n\n # WMI returns the addresses as a tuple of unicode strings, each representing\n # an address/subnet pair. Remove extra spaces that may be present.\n for unnormalized_address in addresses:\n ip_address, subnet = re.split(reg_separator, unnormalized_address)\n if as_wmi_format:\n ret.append('{0}, {1}'.format(ip_address, subnet))\n else:\n ret[ip_address] = subnet\n\n if not ret:\n _LOG.debug('%s is empty.', setting)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing IIS SMTP server configuration on Windows servers.
The Windows features 'SMTP-Server' and 'Web-WMI' must be installed.
:depends: wmi
'''
# IIS metabase configuration settings:
# https://goo.gl/XCt1uO
# IIS logging options:
# https://goo.gl/RL8ki9
# https://goo.gl/iwnDow
# MicrosoftIISv2 namespace in Windows 2008r2 and later:
# http://goo.gl/O4m48T
# Connection and relay IPs in PowerShell:
# https://goo.gl/aBMZ9K
# http://goo.gl/MrybFq
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
# Import Salt libs
from salt.exceptions import SaltInvocationError
import salt.utils.args
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import wmi
import salt.utils.winapi
_HAS_MODULE_DEPENDENCIES = True
except ImportError:
_HAS_MODULE_DEPENDENCIES = False
_DEFAULT_SERVER = 'SmtpSvc/1'
_WMI_NAMESPACE = 'MicrosoftIISv2'
_LOG = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'win_smtp_server'
def __virtual__():
'''
Only works on Windows systems.
'''
if salt.utils.platform.is_windows() and _HAS_MODULE_DEPENDENCIES:
return __virtualname__
return False
def _get_wmi_setting(wmi_class_name, setting, server):
'''
Get the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class([setting], Name=server)[0]
ret = getattr(objs, setting)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
return ret
def _set_wmi_setting(wmi_class_name, setting, value, server):
'''
Set the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class(Name=server)[0]
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
try:
setattr(objs, setting, value)
return True
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except AttributeError as error:
_LOG.error('Error setting %s: %s', setting, error)
return False
def _normalize_server_settings(**settings):
'''
Convert setting values that had been improperly converted to a dict back to a string.
'''
ret = dict()
settings = salt.utils.args.clean_kwargs(**settings)
for setting in settings:
if isinstance(settings[setting], dict):
_LOG.debug('Fixing value: %s', settings[setting])
value_from_key = next(six.iterkeys(settings[setting]))
ret[setting] = "{{{0}}}".format(value_from_key)
else:
ret[setting] = settings[setting]
return ret
def get_log_format_types():
'''
Get all available log format names and ids.
:return: A dictionary of the log format names and ids.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_log_format_types
'''
ret = dict()
prefix = 'logging/'
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IISLogModuleSetting()
# Remove the prefix from the name.
for obj in objs:
name = six.text_type(obj.Name).replace(prefix, '', 1)
ret[name] = six.text_type(obj.LogModuleId)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IISLogModuleSetting: %s', error)
if not ret:
_LOG.error('Unable to get log format types.')
return ret
def get_servers():
'''
Get the SMTP virtual server names.
:return: A list of the SMTP virtual servers.
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_servers
'''
ret = list()
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting()
for obj in objs:
ret.append(six.text_type(obj.Name))
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
_LOG.debug('Found SMTP servers: %s', ret)
return ret
def get_server_setting(settings, server=_DEFAULT_SERVER):
'''
Get the value of the setting for the SMTP virtual server.
:param str settings: A list of the setting names.
:param str server: The SMTP server name.
:return: A dictionary of the provided settings and their values.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_server_setting settings="['MaxRecipients']"
'''
ret = dict()
if not settings:
_LOG.warning('No settings provided.')
return ret
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting(settings, Name=server)[0]
for setting in settings:
ret[setting] = six.text_type(getattr(objs, setting))
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
return ret
def set_server_setting(settings, server=_DEFAULT_SERVER):
'''
Set the value of the setting for the SMTP virtual server.
.. note::
The setting names are case-sensitive.
:param str settings: A dictionary of the setting names and their values.
:param str server: The SMTP server name.
:return: A boolean representing whether all changes succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_server_setting settings="{'MaxRecipients': '500'}"
'''
if not settings:
_LOG.warning('No settings provided')
return False
# Some fields are formatted like '{data}'. Salt tries to convert these to dicts
# automatically on input, so convert them back to the proper format.
settings = _normalize_server_settings(**settings)
current_settings = get_server_setting(settings=settings.keys(), server=server)
if settings == current_settings:
_LOG.debug('Settings already contain the provided values.')
return True
# Note that we must fetch all properties of IIsSmtpServerSetting below, since
# filtering for specific properties and then attempting to set them will cause
# an error like: wmi.x_wmi Unexpected COM Error -2147352567
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting(Name=server)[0]
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(current_settings[setting]):
try:
setattr(objs, setting, settings[setting])
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except AttributeError as error:
_LOG.error('Error setting %s: %s', setting, error)
# Get the settings post-change so that we can verify tht all properties
# were modified successfully. Track the ones that weren't.
new_settings = get_server_setting(settings=settings.keys(), server=server)
failed_settings = dict()
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(new_settings[setting]):
failed_settings[setting] = settings[setting]
if failed_settings:
_LOG.error('Failed to change settings: %s', failed_settings)
return False
_LOG.debug('Settings configured successfully: %s', settings.keys())
return True
def get_log_format(server=_DEFAULT_SERVER):
'''
Get the active log format for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A string of the log format name.
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_log_format
'''
log_format_types = get_log_format_types()
format_id = _get_wmi_setting('IIsSmtpServerSetting', 'LogPluginClsid', server)
# Since IIsSmtpServerSetting stores the log type as an id, we need
# to get the mapping from IISLogModuleSetting and extract the name.
for key in log_format_types:
if six.text_type(format_id) == log_format_types[key]:
return key
_LOG.warning('Unable to determine log format.')
return None
def set_log_format(log_format, server=_DEFAULT_SERVER):
'''
Set the active log format for the SMTP virtual server.
:param str log_format: The log format name.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_log_format 'Microsoft IIS Log File Format'
'''
setting = 'LogPluginClsid'
log_format_types = get_log_format_types()
format_id = log_format_types.get(log_format, None)
if not format_id:
message = ("Invalid log format '{0}' specified. Valid formats:"
' {1}').format(log_format, log_format_types.keys())
raise SaltInvocationError(message)
_LOG.debug("Id for '%s' found: %s", log_format, format_id)
current_log_format = get_log_format(server)
if log_format == current_log_format:
_LOG.debug('%s already contains the provided format.', setting)
return True
_set_wmi_setting('IIsSmtpServerSetting', setting, format_id, server)
new_log_format = get_log_format(server)
ret = log_format == new_log_format
if ret:
_LOG.debug("Setting %s configured successfully: %s", setting, log_format)
else:
_LOG.error("Unable to configure %s with value: %s", setting, log_format)
return ret
def get_connection_ip_list(as_wmi_format=False, server=_DEFAULT_SERVER):
'''
Get the IPGrant list for the SMTP virtual server.
:param bool as_wmi_format: Returns the connection IPs as a list in the format WMI expects.
:param str server: The SMTP server name.
:return: A dictionary of the IP and subnet pairs.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_connection_ip_list
'''
ret = dict()
setting = 'IPGrant'
reg_separator = r',\s*'
if as_wmi_format:
ret = list()
addresses = _get_wmi_setting('IIsIPSecuritySetting', setting, server)
# WMI returns the addresses as a tuple of unicode strings, each representing
# an address/subnet pair. Remove extra spaces that may be present.
for unnormalized_address in addresses:
ip_address, subnet = re.split(reg_separator, unnormalized_address)
if as_wmi_format:
ret.append('{0}, {1}'.format(ip_address, subnet))
else:
ret[ip_address] = subnet
if not ret:
_LOG.debug('%s is empty.', setting)
return ret
def get_relay_ip_list(server=_DEFAULT_SERVER):
'''
Get the RelayIpList list for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A list of the relay IPs.
:rtype: list
.. note::
A return value of None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list, and setting an empty list/tuple corresponds to the more
permissive 'All except the list below' GUI parameter.
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_relay_ip_list
'''
ret = list()
setting = 'RelayIpList'
lines = _get_wmi_setting('IIsSmtpServerSetting', setting, server)
if not lines:
_LOG.debug('%s is empty: %s', setting, lines)
if lines is None:
lines = [None]
return list(lines)
# WMI returns the addresses as a tuple of individual octets, so we
# need to group them and reassemble them into IP addresses.
i = 0
while i < len(lines):
octets = [six.text_type(x) for x in lines[i: i + 4]]
address = '.'.join(octets)
ret.append(address)
i += 4
return ret
def set_relay_ip_list(addresses=None, server=_DEFAULT_SERVER):
'''
Set the RelayIpList list for the SMTP virtual server.
Due to the unusual way that Windows stores the relay IPs, it is advisable to retrieve
the existing list you wish to set from a pre-configured server.
For example, setting '127.0.0.1' as an allowed relay IP through the GUI would generate
an actual relay IP list similar to the following:
.. code-block:: cfg
['24.0.0.128', '32.0.0.128', '60.0.0.128', '68.0.0.128', '1.0.0.0', '76.0.0.0',
'0.0.0.0', '0.0.0.0', '1.0.0.0', '1.0.0.0', '2.0.0.0', '2.0.0.0', '4.0.0.0',
'0.0.0.0', '76.0.0.128', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0',
'255.255.255.255', '127.0.0.1']
.. note::
Setting the list to None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list configured, and setting an empty list/tuple corresponds to the
more permissive 'All except the list below' GUI parameter.
:param str addresses: A list of the relay IPs. The order of the list is important.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_relay_ip_list addresses="['192.168.1.1', '172.16.1.1']"
'''
setting = 'RelayIpList'
formatted_addresses = list()
current_addresses = get_relay_ip_list(server)
if list(addresses) == current_addresses:
_LOG.debug('%s already contains the provided addresses.', setting)
return True
if addresses:
# The WMI input data needs to be in the format used by RelayIpList. Order
# is also important due to the way RelayIpList orders the address list.
if addresses[0] is None:
formatted_addresses = None
else:
for address in addresses:
for octet in address.split('.'):
formatted_addresses.append(octet)
_LOG.debug('Formatted %s addresses: %s', setting, formatted_addresses)
_set_wmi_setting('IIsSmtpServerSetting', setting, formatted_addresses, server)
new_addresses = get_relay_ip_list(server)
ret = list(addresses) == new_addresses
if ret:
_LOG.debug('%s configured successfully: %s', setting, addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, addresses)
return ret
|
saltstack/salt
|
salt/modules/win_smtp_server.py
|
get_relay_ip_list
|
python
|
def get_relay_ip_list(server=_DEFAULT_SERVER):
'''
Get the RelayIpList list for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A list of the relay IPs.
:rtype: list
.. note::
A return value of None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list, and setting an empty list/tuple corresponds to the more
permissive 'All except the list below' GUI parameter.
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_relay_ip_list
'''
ret = list()
setting = 'RelayIpList'
lines = _get_wmi_setting('IIsSmtpServerSetting', setting, server)
if not lines:
_LOG.debug('%s is empty: %s', setting, lines)
if lines is None:
lines = [None]
return list(lines)
# WMI returns the addresses as a tuple of individual octets, so we
# need to group them and reassemble them into IP addresses.
i = 0
while i < len(lines):
octets = [six.text_type(x) for x in lines[i: i + 4]]
address = '.'.join(octets)
ret.append(address)
i += 4
return ret
|
Get the RelayIpList list for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A list of the relay IPs.
:rtype: list
.. note::
A return value of None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list, and setting an empty list/tuple corresponds to the more
permissive 'All except the list below' GUI parameter.
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_relay_ip_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_smtp_server.py#L461-L501
|
[
"def _get_wmi_setting(wmi_class_name, setting, server):\n '''\n Get the value of the setting for the provided class.\n '''\n with salt.utils.winapi.Com():\n try:\n connection = wmi.WMI(namespace=_WMI_NAMESPACE)\n wmi_class = getattr(connection, wmi_class_name)\n\n objs = wmi_class([setting], Name=server)[0]\n ret = getattr(objs, setting)\n except wmi.x_wmi as error:\n _LOG.error('Encountered WMI error: %s', error.com_error)\n except (AttributeError, IndexError) as error:\n _LOG.error('Error getting %s: %s', wmi_class_name, error)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing IIS SMTP server configuration on Windows servers.
The Windows features 'SMTP-Server' and 'Web-WMI' must be installed.
:depends: wmi
'''
# IIS metabase configuration settings:
# https://goo.gl/XCt1uO
# IIS logging options:
# https://goo.gl/RL8ki9
# https://goo.gl/iwnDow
# MicrosoftIISv2 namespace in Windows 2008r2 and later:
# http://goo.gl/O4m48T
# Connection and relay IPs in PowerShell:
# https://goo.gl/aBMZ9K
# http://goo.gl/MrybFq
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
# Import Salt libs
from salt.exceptions import SaltInvocationError
import salt.utils.args
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import wmi
import salt.utils.winapi
_HAS_MODULE_DEPENDENCIES = True
except ImportError:
_HAS_MODULE_DEPENDENCIES = False
_DEFAULT_SERVER = 'SmtpSvc/1'
_WMI_NAMESPACE = 'MicrosoftIISv2'
_LOG = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'win_smtp_server'
def __virtual__():
'''
Only works on Windows systems.
'''
if salt.utils.platform.is_windows() and _HAS_MODULE_DEPENDENCIES:
return __virtualname__
return False
def _get_wmi_setting(wmi_class_name, setting, server):
'''
Get the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class([setting], Name=server)[0]
ret = getattr(objs, setting)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
return ret
def _set_wmi_setting(wmi_class_name, setting, value, server):
'''
Set the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class(Name=server)[0]
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
try:
setattr(objs, setting, value)
return True
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except AttributeError as error:
_LOG.error('Error setting %s: %s', setting, error)
return False
def _normalize_server_settings(**settings):
'''
Convert setting values that had been improperly converted to a dict back to a string.
'''
ret = dict()
settings = salt.utils.args.clean_kwargs(**settings)
for setting in settings:
if isinstance(settings[setting], dict):
_LOG.debug('Fixing value: %s', settings[setting])
value_from_key = next(six.iterkeys(settings[setting]))
ret[setting] = "{{{0}}}".format(value_from_key)
else:
ret[setting] = settings[setting]
return ret
def get_log_format_types():
'''
Get all available log format names and ids.
:return: A dictionary of the log format names and ids.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_log_format_types
'''
ret = dict()
prefix = 'logging/'
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IISLogModuleSetting()
# Remove the prefix from the name.
for obj in objs:
name = six.text_type(obj.Name).replace(prefix, '', 1)
ret[name] = six.text_type(obj.LogModuleId)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IISLogModuleSetting: %s', error)
if not ret:
_LOG.error('Unable to get log format types.')
return ret
def get_servers():
'''
Get the SMTP virtual server names.
:return: A list of the SMTP virtual servers.
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_servers
'''
ret = list()
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting()
for obj in objs:
ret.append(six.text_type(obj.Name))
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
_LOG.debug('Found SMTP servers: %s', ret)
return ret
def get_server_setting(settings, server=_DEFAULT_SERVER):
'''
Get the value of the setting for the SMTP virtual server.
:param str settings: A list of the setting names.
:param str server: The SMTP server name.
:return: A dictionary of the provided settings and their values.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_server_setting settings="['MaxRecipients']"
'''
ret = dict()
if not settings:
_LOG.warning('No settings provided.')
return ret
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting(settings, Name=server)[0]
for setting in settings:
ret[setting] = six.text_type(getattr(objs, setting))
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
return ret
def set_server_setting(settings, server=_DEFAULT_SERVER):
'''
Set the value of the setting for the SMTP virtual server.
.. note::
The setting names are case-sensitive.
:param str settings: A dictionary of the setting names and their values.
:param str server: The SMTP server name.
:return: A boolean representing whether all changes succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_server_setting settings="{'MaxRecipients': '500'}"
'''
if not settings:
_LOG.warning('No settings provided')
return False
# Some fields are formatted like '{data}'. Salt tries to convert these to dicts
# automatically on input, so convert them back to the proper format.
settings = _normalize_server_settings(**settings)
current_settings = get_server_setting(settings=settings.keys(), server=server)
if settings == current_settings:
_LOG.debug('Settings already contain the provided values.')
return True
# Note that we must fetch all properties of IIsSmtpServerSetting below, since
# filtering for specific properties and then attempting to set them will cause
# an error like: wmi.x_wmi Unexpected COM Error -2147352567
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting(Name=server)[0]
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(current_settings[setting]):
try:
setattr(objs, setting, settings[setting])
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except AttributeError as error:
_LOG.error('Error setting %s: %s', setting, error)
# Get the settings post-change so that we can verify tht all properties
# were modified successfully. Track the ones that weren't.
new_settings = get_server_setting(settings=settings.keys(), server=server)
failed_settings = dict()
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(new_settings[setting]):
failed_settings[setting] = settings[setting]
if failed_settings:
_LOG.error('Failed to change settings: %s', failed_settings)
return False
_LOG.debug('Settings configured successfully: %s', settings.keys())
return True
def get_log_format(server=_DEFAULT_SERVER):
'''
Get the active log format for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A string of the log format name.
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_log_format
'''
log_format_types = get_log_format_types()
format_id = _get_wmi_setting('IIsSmtpServerSetting', 'LogPluginClsid', server)
# Since IIsSmtpServerSetting stores the log type as an id, we need
# to get the mapping from IISLogModuleSetting and extract the name.
for key in log_format_types:
if six.text_type(format_id) == log_format_types[key]:
return key
_LOG.warning('Unable to determine log format.')
return None
def set_log_format(log_format, server=_DEFAULT_SERVER):
'''
Set the active log format for the SMTP virtual server.
:param str log_format: The log format name.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_log_format 'Microsoft IIS Log File Format'
'''
setting = 'LogPluginClsid'
log_format_types = get_log_format_types()
format_id = log_format_types.get(log_format, None)
if not format_id:
message = ("Invalid log format '{0}' specified. Valid formats:"
' {1}').format(log_format, log_format_types.keys())
raise SaltInvocationError(message)
_LOG.debug("Id for '%s' found: %s", log_format, format_id)
current_log_format = get_log_format(server)
if log_format == current_log_format:
_LOG.debug('%s already contains the provided format.', setting)
return True
_set_wmi_setting('IIsSmtpServerSetting', setting, format_id, server)
new_log_format = get_log_format(server)
ret = log_format == new_log_format
if ret:
_LOG.debug("Setting %s configured successfully: %s", setting, log_format)
else:
_LOG.error("Unable to configure %s with value: %s", setting, log_format)
return ret
def get_connection_ip_list(as_wmi_format=False, server=_DEFAULT_SERVER):
'''
Get the IPGrant list for the SMTP virtual server.
:param bool as_wmi_format: Returns the connection IPs as a list in the format WMI expects.
:param str server: The SMTP server name.
:return: A dictionary of the IP and subnet pairs.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_connection_ip_list
'''
ret = dict()
setting = 'IPGrant'
reg_separator = r',\s*'
if as_wmi_format:
ret = list()
addresses = _get_wmi_setting('IIsIPSecuritySetting', setting, server)
# WMI returns the addresses as a tuple of unicode strings, each representing
# an address/subnet pair. Remove extra spaces that may be present.
for unnormalized_address in addresses:
ip_address, subnet = re.split(reg_separator, unnormalized_address)
if as_wmi_format:
ret.append('{0}, {1}'.format(ip_address, subnet))
else:
ret[ip_address] = subnet
if not ret:
_LOG.debug('%s is empty.', setting)
return ret
def set_connection_ip_list(addresses=None, grant_by_default=False, server=_DEFAULT_SERVER):
'''
Set the IPGrant list for the SMTP virtual server.
:param str addresses: A dictionary of IP + subnet pairs.
:param bool grant_by_default: Whether the addresses should be a blacklist or whitelist.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_connection_ip_list addresses="{'127.0.0.1': '255.255.255.255'}"
'''
setting = 'IPGrant'
formatted_addresses = list()
# It's okay to accept an empty list for set_connection_ip_list,
# since an empty list may be desirable.
if not addresses:
addresses = dict()
_LOG.debug('Empty %s specified.', setting)
# Convert addresses to the 'ip_address, subnet' format used by
# IIsIPSecuritySetting.
for address in addresses:
formatted_addresses.append('{0}, {1}'.format(address.strip(),
addresses[address].strip()))
current_addresses = get_connection_ip_list(as_wmi_format=True, server=server)
# Order is not important, so compare to the current addresses as unordered sets.
if set(formatted_addresses) == set(current_addresses):
_LOG.debug('%s already contains the provided addresses.', setting)
return True
# First we should check GrantByDefault, and change it if necessary.
current_grant_by_default = _get_wmi_setting('IIsIPSecuritySetting', 'GrantByDefault', server)
if grant_by_default != current_grant_by_default:
_LOG.debug('Setting GrantByDefault to: %s', grant_by_default)
_set_wmi_setting('IIsIPSecuritySetting', 'GrantByDefault', grant_by_default, server)
_set_wmi_setting('IIsIPSecuritySetting', setting, formatted_addresses, server)
new_addresses = get_connection_ip_list(as_wmi_format=True, server=server)
ret = set(formatted_addresses) == set(new_addresses)
if ret:
_LOG.debug('%s configured successfully: %s', setting, formatted_addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, formatted_addresses)
return ret
def set_relay_ip_list(addresses=None, server=_DEFAULT_SERVER):
'''
Set the RelayIpList list for the SMTP virtual server.
Due to the unusual way that Windows stores the relay IPs, it is advisable to retrieve
the existing list you wish to set from a pre-configured server.
For example, setting '127.0.0.1' as an allowed relay IP through the GUI would generate
an actual relay IP list similar to the following:
.. code-block:: cfg
['24.0.0.128', '32.0.0.128', '60.0.0.128', '68.0.0.128', '1.0.0.0', '76.0.0.0',
'0.0.0.0', '0.0.0.0', '1.0.0.0', '1.0.0.0', '2.0.0.0', '2.0.0.0', '4.0.0.0',
'0.0.0.0', '76.0.0.128', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0',
'255.255.255.255', '127.0.0.1']
.. note::
Setting the list to None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list configured, and setting an empty list/tuple corresponds to the
more permissive 'All except the list below' GUI parameter.
:param str addresses: A list of the relay IPs. The order of the list is important.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_relay_ip_list addresses="['192.168.1.1', '172.16.1.1']"
'''
setting = 'RelayIpList'
formatted_addresses = list()
current_addresses = get_relay_ip_list(server)
if list(addresses) == current_addresses:
_LOG.debug('%s already contains the provided addresses.', setting)
return True
if addresses:
# The WMI input data needs to be in the format used by RelayIpList. Order
# is also important due to the way RelayIpList orders the address list.
if addresses[0] is None:
formatted_addresses = None
else:
for address in addresses:
for octet in address.split('.'):
formatted_addresses.append(octet)
_LOG.debug('Formatted %s addresses: %s', setting, formatted_addresses)
_set_wmi_setting('IIsSmtpServerSetting', setting, formatted_addresses, server)
new_addresses = get_relay_ip_list(server)
ret = list(addresses) == new_addresses
if ret:
_LOG.debug('%s configured successfully: %s', setting, addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, addresses)
return ret
|
saltstack/salt
|
salt/modules/win_smtp_server.py
|
set_relay_ip_list
|
python
|
def set_relay_ip_list(addresses=None, server=_DEFAULT_SERVER):
'''
Set the RelayIpList list for the SMTP virtual server.
Due to the unusual way that Windows stores the relay IPs, it is advisable to retrieve
the existing list you wish to set from a pre-configured server.
For example, setting '127.0.0.1' as an allowed relay IP through the GUI would generate
an actual relay IP list similar to the following:
.. code-block:: cfg
['24.0.0.128', '32.0.0.128', '60.0.0.128', '68.0.0.128', '1.0.0.0', '76.0.0.0',
'0.0.0.0', '0.0.0.0', '1.0.0.0', '1.0.0.0', '2.0.0.0', '2.0.0.0', '4.0.0.0',
'0.0.0.0', '76.0.0.128', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0',
'255.255.255.255', '127.0.0.1']
.. note::
Setting the list to None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list configured, and setting an empty list/tuple corresponds to the
more permissive 'All except the list below' GUI parameter.
:param str addresses: A list of the relay IPs. The order of the list is important.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_relay_ip_list addresses="['192.168.1.1', '172.16.1.1']"
'''
setting = 'RelayIpList'
formatted_addresses = list()
current_addresses = get_relay_ip_list(server)
if list(addresses) == current_addresses:
_LOG.debug('%s already contains the provided addresses.', setting)
return True
if addresses:
# The WMI input data needs to be in the format used by RelayIpList. Order
# is also important due to the way RelayIpList orders the address list.
if addresses[0] is None:
formatted_addresses = None
else:
for address in addresses:
for octet in address.split('.'):
formatted_addresses.append(octet)
_LOG.debug('Formatted %s addresses: %s', setting, formatted_addresses)
_set_wmi_setting('IIsSmtpServerSetting', setting, formatted_addresses, server)
new_addresses = get_relay_ip_list(server)
ret = list(addresses) == new_addresses
if ret:
_LOG.debug('%s configured successfully: %s', setting, addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, addresses)
return ret
|
Set the RelayIpList list for the SMTP virtual server.
Due to the unusual way that Windows stores the relay IPs, it is advisable to retrieve
the existing list you wish to set from a pre-configured server.
For example, setting '127.0.0.1' as an allowed relay IP through the GUI would generate
an actual relay IP list similar to the following:
.. code-block:: cfg
['24.0.0.128', '32.0.0.128', '60.0.0.128', '68.0.0.128', '1.0.0.0', '76.0.0.0',
'0.0.0.0', '0.0.0.0', '1.0.0.0', '1.0.0.0', '2.0.0.0', '2.0.0.0', '4.0.0.0',
'0.0.0.0', '76.0.0.128', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0',
'255.255.255.255', '127.0.0.1']
.. note::
Setting the list to None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list configured, and setting an empty list/tuple corresponds to the
more permissive 'All except the list below' GUI parameter.
:param str addresses: A list of the relay IPs. The order of the list is important.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_relay_ip_list addresses="['192.168.1.1', '172.16.1.1']"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_smtp_server.py#L504-L571
|
[
"def get_relay_ip_list(server=_DEFAULT_SERVER):\n '''\n Get the RelayIpList list for the SMTP virtual server.\n\n :param str server: The SMTP server name.\n\n :return: A list of the relay IPs.\n :rtype: list\n\n .. note::\n\n A return value of None corresponds to the restrictive 'Only the list below' GUI parameter\n with an empty access list, and setting an empty list/tuple corresponds to the more\n permissive 'All except the list below' GUI parameter.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_smtp_server.get_relay_ip_list\n '''\n ret = list()\n setting = 'RelayIpList'\n\n lines = _get_wmi_setting('IIsSmtpServerSetting', setting, server)\n\n if not lines:\n _LOG.debug('%s is empty: %s', setting, lines)\n if lines is None:\n lines = [None]\n return list(lines)\n\n # WMI returns the addresses as a tuple of individual octets, so we\n # need to group them and reassemble them into IP addresses.\n i = 0\n while i < len(lines):\n octets = [six.text_type(x) for x in lines[i: i + 4]]\n address = '.'.join(octets)\n ret.append(address)\n i += 4\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing IIS SMTP server configuration on Windows servers.
The Windows features 'SMTP-Server' and 'Web-WMI' must be installed.
:depends: wmi
'''
# IIS metabase configuration settings:
# https://goo.gl/XCt1uO
# IIS logging options:
# https://goo.gl/RL8ki9
# https://goo.gl/iwnDow
# MicrosoftIISv2 namespace in Windows 2008r2 and later:
# http://goo.gl/O4m48T
# Connection and relay IPs in PowerShell:
# https://goo.gl/aBMZ9K
# http://goo.gl/MrybFq
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import re
# Import Salt libs
from salt.exceptions import SaltInvocationError
import salt.utils.args
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import wmi
import salt.utils.winapi
_HAS_MODULE_DEPENDENCIES = True
except ImportError:
_HAS_MODULE_DEPENDENCIES = False
_DEFAULT_SERVER = 'SmtpSvc/1'
_WMI_NAMESPACE = 'MicrosoftIISv2'
_LOG = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'win_smtp_server'
def __virtual__():
'''
Only works on Windows systems.
'''
if salt.utils.platform.is_windows() and _HAS_MODULE_DEPENDENCIES:
return __virtualname__
return False
def _get_wmi_setting(wmi_class_name, setting, server):
'''
Get the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class([setting], Name=server)[0]
ret = getattr(objs, setting)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
return ret
def _set_wmi_setting(wmi_class_name, setting, value, server):
'''
Set the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class(Name=server)[0]
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
try:
setattr(objs, setting, value)
return True
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except AttributeError as error:
_LOG.error('Error setting %s: %s', setting, error)
return False
def _normalize_server_settings(**settings):
'''
Convert setting values that had been improperly converted to a dict back to a string.
'''
ret = dict()
settings = salt.utils.args.clean_kwargs(**settings)
for setting in settings:
if isinstance(settings[setting], dict):
_LOG.debug('Fixing value: %s', settings[setting])
value_from_key = next(six.iterkeys(settings[setting]))
ret[setting] = "{{{0}}}".format(value_from_key)
else:
ret[setting] = settings[setting]
return ret
def get_log_format_types():
'''
Get all available log format names and ids.
:return: A dictionary of the log format names and ids.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_log_format_types
'''
ret = dict()
prefix = 'logging/'
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IISLogModuleSetting()
# Remove the prefix from the name.
for obj in objs:
name = six.text_type(obj.Name).replace(prefix, '', 1)
ret[name] = six.text_type(obj.LogModuleId)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IISLogModuleSetting: %s', error)
if not ret:
_LOG.error('Unable to get log format types.')
return ret
def get_servers():
'''
Get the SMTP virtual server names.
:return: A list of the SMTP virtual servers.
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_servers
'''
ret = list()
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting()
for obj in objs:
ret.append(six.text_type(obj.Name))
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
_LOG.debug('Found SMTP servers: %s', ret)
return ret
def get_server_setting(settings, server=_DEFAULT_SERVER):
'''
Get the value of the setting for the SMTP virtual server.
:param str settings: A list of the setting names.
:param str server: The SMTP server name.
:return: A dictionary of the provided settings and their values.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_server_setting settings="['MaxRecipients']"
'''
ret = dict()
if not settings:
_LOG.warning('No settings provided.')
return ret
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting(settings, Name=server)[0]
for setting in settings:
ret[setting] = six.text_type(getattr(objs, setting))
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
return ret
def set_server_setting(settings, server=_DEFAULT_SERVER):
'''
Set the value of the setting for the SMTP virtual server.
.. note::
The setting names are case-sensitive.
:param str settings: A dictionary of the setting names and their values.
:param str server: The SMTP server name.
:return: A boolean representing whether all changes succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_server_setting settings="{'MaxRecipients': '500'}"
'''
if not settings:
_LOG.warning('No settings provided')
return False
# Some fields are formatted like '{data}'. Salt tries to convert these to dicts
# automatically on input, so convert them back to the proper format.
settings = _normalize_server_settings(**settings)
current_settings = get_server_setting(settings=settings.keys(), server=server)
if settings == current_settings:
_LOG.debug('Settings already contain the provided values.')
return True
# Note that we must fetch all properties of IIsSmtpServerSetting below, since
# filtering for specific properties and then attempting to set them will cause
# an error like: wmi.x_wmi Unexpected COM Error -2147352567
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
objs = connection.IIsSmtpServerSetting(Name=server)[0]
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting IIsSmtpServerSetting: %s', error)
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(current_settings[setting]):
try:
setattr(objs, setting, settings[setting])
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except AttributeError as error:
_LOG.error('Error setting %s: %s', setting, error)
# Get the settings post-change so that we can verify tht all properties
# were modified successfully. Track the ones that weren't.
new_settings = get_server_setting(settings=settings.keys(), server=server)
failed_settings = dict()
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(new_settings[setting]):
failed_settings[setting] = settings[setting]
if failed_settings:
_LOG.error('Failed to change settings: %s', failed_settings)
return False
_LOG.debug('Settings configured successfully: %s', settings.keys())
return True
def get_log_format(server=_DEFAULT_SERVER):
'''
Get the active log format for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A string of the log format name.
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_log_format
'''
log_format_types = get_log_format_types()
format_id = _get_wmi_setting('IIsSmtpServerSetting', 'LogPluginClsid', server)
# Since IIsSmtpServerSetting stores the log type as an id, we need
# to get the mapping from IISLogModuleSetting and extract the name.
for key in log_format_types:
if six.text_type(format_id) == log_format_types[key]:
return key
_LOG.warning('Unable to determine log format.')
return None
def set_log_format(log_format, server=_DEFAULT_SERVER):
'''
Set the active log format for the SMTP virtual server.
:param str log_format: The log format name.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_log_format 'Microsoft IIS Log File Format'
'''
setting = 'LogPluginClsid'
log_format_types = get_log_format_types()
format_id = log_format_types.get(log_format, None)
if not format_id:
message = ("Invalid log format '{0}' specified. Valid formats:"
' {1}').format(log_format, log_format_types.keys())
raise SaltInvocationError(message)
_LOG.debug("Id for '%s' found: %s", log_format, format_id)
current_log_format = get_log_format(server)
if log_format == current_log_format:
_LOG.debug('%s already contains the provided format.', setting)
return True
_set_wmi_setting('IIsSmtpServerSetting', setting, format_id, server)
new_log_format = get_log_format(server)
ret = log_format == new_log_format
if ret:
_LOG.debug("Setting %s configured successfully: %s", setting, log_format)
else:
_LOG.error("Unable to configure %s with value: %s", setting, log_format)
return ret
def get_connection_ip_list(as_wmi_format=False, server=_DEFAULT_SERVER):
'''
Get the IPGrant list for the SMTP virtual server.
:param bool as_wmi_format: Returns the connection IPs as a list in the format WMI expects.
:param str server: The SMTP server name.
:return: A dictionary of the IP and subnet pairs.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_connection_ip_list
'''
ret = dict()
setting = 'IPGrant'
reg_separator = r',\s*'
if as_wmi_format:
ret = list()
addresses = _get_wmi_setting('IIsIPSecuritySetting', setting, server)
# WMI returns the addresses as a tuple of unicode strings, each representing
# an address/subnet pair. Remove extra spaces that may be present.
for unnormalized_address in addresses:
ip_address, subnet = re.split(reg_separator, unnormalized_address)
if as_wmi_format:
ret.append('{0}, {1}'.format(ip_address, subnet))
else:
ret[ip_address] = subnet
if not ret:
_LOG.debug('%s is empty.', setting)
return ret
def set_connection_ip_list(addresses=None, grant_by_default=False, server=_DEFAULT_SERVER):
'''
Set the IPGrant list for the SMTP virtual server.
:param str addresses: A dictionary of IP + subnet pairs.
:param bool grant_by_default: Whether the addresses should be a blacklist or whitelist.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_connection_ip_list addresses="{'127.0.0.1': '255.255.255.255'}"
'''
setting = 'IPGrant'
formatted_addresses = list()
# It's okay to accept an empty list for set_connection_ip_list,
# since an empty list may be desirable.
if not addresses:
addresses = dict()
_LOG.debug('Empty %s specified.', setting)
# Convert addresses to the 'ip_address, subnet' format used by
# IIsIPSecuritySetting.
for address in addresses:
formatted_addresses.append('{0}, {1}'.format(address.strip(),
addresses[address].strip()))
current_addresses = get_connection_ip_list(as_wmi_format=True, server=server)
# Order is not important, so compare to the current addresses as unordered sets.
if set(formatted_addresses) == set(current_addresses):
_LOG.debug('%s already contains the provided addresses.', setting)
return True
# First we should check GrantByDefault, and change it if necessary.
current_grant_by_default = _get_wmi_setting('IIsIPSecuritySetting', 'GrantByDefault', server)
if grant_by_default != current_grant_by_default:
_LOG.debug('Setting GrantByDefault to: %s', grant_by_default)
_set_wmi_setting('IIsIPSecuritySetting', 'GrantByDefault', grant_by_default, server)
_set_wmi_setting('IIsIPSecuritySetting', setting, formatted_addresses, server)
new_addresses = get_connection_ip_list(as_wmi_format=True, server=server)
ret = set(formatted_addresses) == set(new_addresses)
if ret:
_LOG.debug('%s configured successfully: %s', setting, formatted_addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, formatted_addresses)
return ret
def get_relay_ip_list(server=_DEFAULT_SERVER):
'''
Get the RelayIpList list for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A list of the relay IPs.
:rtype: list
.. note::
A return value of None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list, and setting an empty list/tuple corresponds to the more
permissive 'All except the list below' GUI parameter.
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.get_relay_ip_list
'''
ret = list()
setting = 'RelayIpList'
lines = _get_wmi_setting('IIsSmtpServerSetting', setting, server)
if not lines:
_LOG.debug('%s is empty: %s', setting, lines)
if lines is None:
lines = [None]
return list(lines)
# WMI returns the addresses as a tuple of individual octets, so we
# need to group them and reassemble them into IP addresses.
i = 0
while i < len(lines):
octets = [six.text_type(x) for x in lines[i: i + 4]]
address = '.'.join(octets)
ret.append(address)
i += 4
return ret
|
saltstack/salt
|
salt/modules/netmiko_mod.py
|
_prepare_connection
|
python
|
def _prepare_connection(**kwargs):
'''
Prepare the connection with the remote network device, and clean up the key
value pairs, removing the args used for the connection init.
'''
init_args = {}
fun_kwargs = {}
netmiko_kwargs = __salt__['config.get']('netmiko', {})
netmiko_kwargs.update(kwargs) # merge the CLI args with the opts/pillar
netmiko_init_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)
check_self = netmiko_init_args.pop(0)
for karg, warg in six.iteritems(netmiko_kwargs):
if karg not in netmiko_init_args:
if warg is not None:
fun_kwargs[karg] = warg
continue
if warg is not None:
init_args[karg] = warg
conn = ConnectHandler(**init_args)
return conn, fun_kwargs
|
Prepare the connection with the remote network device, and clean up the key
value pairs, removing the args used for the connection init.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netmiko_mod.py#L241-L260
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Netmiko Execution Module
========================
.. versionadded:: 2019.2.0
Execution module to interface the connection with a remote network device. It is
flexible enough to execute the commands both when running under a Netmiko Proxy
Minion, as well as running under a Regular Minion by specifying the connection
arguments, i.e., ``device_type``, ``ip``, ``username``, ``password`` etc.
:codeauthor: Mircea Ulinic <ping@mirceaulinic.net> & Kirk Byers <ktbyers@twb-tech.com>
:maturity: new
:depends: netmiko
:platform: unix
Dependencies
------------
The ``netmiko`` proxy modules requires Netmiko to be installed: ``pip install netmiko``.
Usage
-----
This module can equally be used via the :mod:`netmiko <salt.proxy.netmiko_px>`
Proxy module (check documentation), or directly from an arbitrary (Proxy) Minion
that is running on a server (computer) having access to the network device, and
has the ``netmiko`` library installed.
When running outside of the :mod:`netmiko Proxy <salt.proxy.netmiko_px>` (i.e.,
from another Proxy Minion type, or regular Minion), the netmiko connection
arguments can be either specified from the CLI when executing the command, or
in a configuration block under the ``netmiko`` key in the configuration opts
(i.e., (Proxy) Minion configuration file), or Pillar. The module supports these
simultaneously. These fields are the exact same supported by the ``netmiko``
Proxy Module:
- ``device_type`` - Class selection based on device type. Supported options:
- ``a10``: A10 Networks
- ``accedian``: Accedian Networks
- ``alcatel_aos``: Alcatel AOS
- ``alcatel_sros``: Alcatel SROS
- ``apresia_aeos``: Apresia AEOS
- ``arista_eos``: Arista EOS
- ``aruba_os``: Aruba
- ``avaya_ers``: Avaya ERS
- ``avaya_vsp``: Avaya VSP
- ``brocade_fastiron``: Brocade Fastiron
- ``brocade_netiron``: Brocade Netiron
- ``brocade_nos``: Brocade NOS
- ``brocade_vdx``: Brocade NOS
- ``brocade_vyos``: VyOS
- ``checkpoint_gaia``: Check Point GAiA
- ``calix_b6``: Calix B6
- ``ciena_saos``: Ciena SAOS
- ``cisco_asa``: Cisco SA
- ``cisco_ios``: Cisco IOS
- ``cisco_nxos``: Cisco NX-oS
- ``cisco_s300``: Cisco S300
- ``cisco_tp``: Cisco TpTcCe
- ``cisco_wlc``: Cisco WLC
- ``cisco_xe``: Cisco IOS
- ``cisco_xr``: Cisco XR
- ``coriant``: Coriant
- ``dell_force10``: Dell Force10
- ``dell_os10``: Dell OS10
- ``dell_powerconnect``: Dell PowerConnect
- ``eltex``: Eltex
- ``enterasys``: Enterasys
- ``extreme``: Extreme
- ``extreme_wing``: Extreme Wing
- ``f5_ltm``: F5 LTM
- ``fortinet``: Fortinet
- ``generic_termserver``: TerminalServer
- ``hp_comware``: HP Comware
- ``hp_procurve``: HP Procurve
- ``huawei``: Huawei
- ``huawei_vrpv8``: Huawei VRPV8
- ``juniper``: Juniper Junos
- ``juniper_junos``: Juniper Junos
- ``linux``: Linux
- ``mellanox``: Mellanox
- ``mrv_optiswitch``: MrvOptiswitch
- ``netapp_cdot``: NetAppcDot
- ``netscaler``: Netscaler
- ``ovs_linux``: OvsLinux
- ``paloalto_panos``: PaloAlto Panos
- ``pluribus``: Pluribus
- ``quanta_mesh``: Quanta Mesh
- ``ruckus_fastiron``: Ruckus Fastiron
- ``ubiquiti_edge``: Ubiquiti Edge
- ``ubiquiti_edgeswitch``: Ubiquiti Edge
- ``vyatta_vyos``: VyOS
- ``vyos``: VyOS
- ``brocade_fastiron_telnet``: Brocade Fastiron over Telnet
- ``brocade_netiron_telnet``: Brocade Netiron over Telnet
- ``cisco_ios_telnet``: Cisco IOS over Telnet
- ``apresia_aeos_telnet``: Apresia AEOS over Telnet
- ``arista_eos_telnet``: Arista EOS over Telnet
- ``hp_procurve_telnet``: HP Procurve over Telnet
- ``hp_comware_telnet``: HP Comware over Telnet
- ``juniper_junos_telnet``: Juniper Junos over Telnet
- ``calix_b6_telnet``: Calix B6 over Telnet
- ``dell_powerconnect_telnet``: Dell PowerConnect over Telnet
- ``generic_termserver_telnet``: TerminalServer over Telnet
- ``extreme_telnet``: Extreme Networks over Telnet
- ``ruckus_fastiron_telnet``: Ruckus Fastiron over Telnet
- ``cisco_ios_serial``: Cisco IOS over serial port
- ``ip`` - IP address of target device (not required if ``host`` is provided)
- ``host`` - Hostname of target device (not required if ``ip`` is provided)
- ``username`` - Username to authenticate against target device, if required
- ``password`` - Password to authenticate against target device, if required
- ``secret`` - The enable password if target device requires one
- ``port`` - The destination port used to connect to the target device
- ``global_delay_factor`` - Multiplication factor affecting Netmiko delays
(default: ``1``)
- ``use_keys`` - Connect to target device using SSH keys (default: ``False``)
- ``key_file`` - Filename path of the SSH key file to use
- ``allow_agent`` - Enable use of SSH key-agent
- ``ssh_strict`` - Automatically reject unknown SSH host keys (default:
``False``, which means unknown SSH host keys will be accepted)
- ``system_host_keys`` - Load host keys from the user's "known_hosts" file
(default: ``False``)
- ``alt_host_keys`` - If ``True``, host keys will be loaded from the file
specified in ``alt_key_file`` (default: ``False``)
- ``alt_key_file`` - SSH host key file to use (if ``alt_host_keys=True``)
- ``ssh_config_file`` - File name of OpenSSH configuration file
- ``timeout`` - Connection timeout, in seconds (default: ``90``)
- ``session_timeout`` - Set a timeout for parallel requests, in seconds
(default: ``60``)
- ``keepalive`` - Send SSH keepalive packets at a specific interval, in
seconds. Currently defaults to ``0``, for backwards compatibility (it will
not attempt to keep the connection alive using the KEEPALIVE packets).
- ``default_enter`` - Character(s) to send to correspond to enter key (default:
``\\n``)
- ``response_return`` - Character(s) to use in normalized return data to
represent enter key (default: ``\\n``)
Example (when not running in a ``netmiko`` Proxy Minion):
.. code-block:: yaml
netmiko:
username: test
password: test
In case the ``username`` and ``password`` are the same on any device you are
targeting, the block above (besides other parameters specific to your
environment you might need) should suffice to be able to execute commands from
outside a ``netmiko`` Proxy, e.g.:
.. code-block:: bash
salt '*' netmiko.send_command 'show version' host=router1.example.com device_type=juniper
salt '*' netmiko.send_config https://bit.ly/2sgljCB host=sw2.example.com device_type=cisco_ios
.. note::
Remember that the above applies only when not running in a ``netmiko`` Proxy
Minion. If you want to use the :mod:`<salt.proxy.netmiko_px>`, please follow
the documentation notes for a proper setup.
'''
from __future__ import absolute_import
# Import python stdlib
import logging
import inspect
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
try:
from salt.utils.args import clean_kwargs
except ImportError:
from salt.utils import clean_kwargs
# Import third party libs
try:
from netmiko import ConnectHandler
from netmiko import BaseConnection
HAS_NETMIKO = True
except ImportError:
HAS_NETMIKO = False
# -----------------------------------------------------------------------------
# execution module properties
# -----------------------------------------------------------------------------
__proxyenabled__ = ['*']
# Any Proxy Minion should be able to execute these (not only netmiko)
__virtualname__ = 'netmiko'
# The Execution Module will be identified as ``netmiko``
# -----------------------------------------------------------------------------
# globals
# -----------------------------------------------------------------------------
log = logging.getLogger(__name__)
# -----------------------------------------------------------------------------
# propery functions
# -----------------------------------------------------------------------------
def __virtual__():
'''
Execution module available only if Netmiko is installed.
'''
if not HAS_NETMIKO:
return False, 'The netmiko execution module requires netmiko library to be installed.'
return __virtualname__
# -----------------------------------------------------------------------------
# helper functions
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# callable functions
# -----------------------------------------------------------------------------
def get_connection(**kwargs):
'''
Return the Netmiko connection object.
.. warning::
This function returns an unserializable object, hence it is not meant
to be used on the CLI. This should mainly be used when invoked from
other modules for the low level connection with the network device.
kwargs
Key-value dictionary with the authentication details.
USAGE Example:
.. code-block:: python
conn = __salt__['netmiko.get_connection'](host='router1.example.com',
username='example',
password='example')
show_if = conn.send_command('show interfaces')
conn.disconnect()
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
return __proxy__['netmiko.conn']()
conn, kwargs = _prepare_connection(**kwargs)
return conn
def call(method, *args, **kwargs):
'''
Invoke an arbitrary Netmiko method.
method
The name of the Netmiko method to invoke.
args
A list of arguments to send to the method invoked.
kwargs
Key-value dictionary to send to the method invoked.
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.call' in __proxy__:
return __proxy__['netmiko.call'](method, *args, **kwargs)
conn, kwargs = _prepare_connection(**kwargs)
ret = getattr(conn, method)(*args, **kwargs)
conn.disconnect()
return ret
def multi_call(*methods, **kwargs):
'''
Invoke multiple Netmiko methods at once, and return their output, as list.
methods
A list of dictionaries with the following keys:
- ``name``: the name of the Netmiko method to be executed.
- ``args``: list of arguments to be sent to the Netmiko method.
- ``kwargs``: dictionary of arguments to be sent to the Netmiko method.
kwargs
Key-value dictionary with the connection details (when not running
under a Proxy Minion).
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
conn = __proxy__['netmiko.conn']()
else:
conn, kwargs = _prepare_connection(**kwargs)
ret = []
for method in methods:
# Explicit unpacking
method_name = method['name']
method_args = method.get('args', [])
method_kwargs = method.get('kwargs', [])
ret.append(getattr(conn, method_name)(*method_args, **method_kwargs))
if 'netmiko.conn' not in __proxy__:
conn.disconnect()
return ret
def send_command(command_string, **kwargs):
'''
Execute command_string on the SSH channel using a pattern-based mechanism.
Generally used for show commands. By default this method will keep waiting
to receive data until the network device prompt is detected. The current
network device prompt will be determined automatically.
command_string
The command to be executed on the remote device.
expect_string
Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
auto_find_prompt: ``True``
Whether it should try to auto-detect the prompt (default: ``True``).
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_command 'show version'
salt '*' netmiko.send_command 'show_version' host='router1.example.com' username='example' device_type='cisco_ios'
'''
return call('send_command', command_string, **kwargs)
def send_command_timing(command_string, **kwargs):
'''
Execute command_string on the SSH channel using a delay-based mechanism.
Generally used for show commands.
command_string
The command to be executed on the remote device.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_command_timing 'show version'
salt '*' netmiko.send_command_timing 'show version' host='router1.example.com' username='example' device_type='arista_eos'
'''
return call('send_command_timing', command_string, **kwargs)
def enter_config_mode(**kwargs):
'''
Enter into config mode.
config_command
Configuration command to send to the device.
pattern
Pattern to terminate reading of channel.
CLI Example:
.. code-block:: bash
salt '*' netmiko.enter_config_mode
salt '*' netmiko.enter_config_mode device_type='juniper_junos' ip='192.168.0.1' username='example'
'''
return call('config_mode', **kwargs)
def exit_config_mode(**kwargs):
'''
Exit from configuration mode.
exit_config
Command to exit configuration mode.
pattern
Pattern to terminate reading of channel.
CLI Example:
.. code-block:: bash
salt '*' netmiko.exit_config_mode
salt '*' netmiko.exit_config_mode device_type='juniper' ip='192.168.0.1' username='example'
'''
return call('exit_config_mode', **kwargs)
def send_config(config_file=None,
config_commands=None,
template_engine='jinja',
commit=False,
context=None,
defaults=None,
saltenv='base',
**kwargs):
'''
Send configuration commands down the SSH channel.
Return the configuration lines sent to the device.
The function is flexible to send the configuration from a local or remote
file, or simply the commands as list.
config_file
The source file with the configuration commands to be sent to the
device.
The file can also be a template that can be rendered using the template
engine of choice.
This can be specified using the absolute path to the file, or using one
of the following URL schemes:
- ``salt://``, to fetch the file from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
config_commands
Multiple configuration commands to be sent to the device.
.. note::
This argument is ignored when ``config_file`` is specified.
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
commit: ``False``
Commit the configuration changes before exiting the config mode. This
option is by default disabled, as many platforms don't have this
capability natively.
context
Variables to add to the template context.
defaults
Default values of the context_dict.
exit_config_mode: ``True``
Determines whether or not to exit config mode after complete.
delay_factor: ``1``
Factor to adjust delays.
max_loops: ``150``
Controls wait time in conjunction with delay_factor (default: ``150``).
strip_prompt: ``False``
Determines whether or not to strip the prompt (default: ``False``).
strip_command: ``False``
Determines whether or not to strip the command (default: ``False``).
config_mode_command
The command to enter into config mode.
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_config config_commands="['interface GigabitEthernet3', 'no ip address']"
salt '*' netmiko.send_config config_commands="['snmp-server location {{ grains.location }}']"
salt '*' netmiko.send_config config_file=salt://config.txt
salt '*' netmiko.send_config config_file=https://bit.ly/2sgljCB device_type='cisco_ios' ip='1.2.3.4' username='example'
'''
if config_file:
file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv)
if file_str is False:
raise CommandExecutionError('Source file {} not found'.format(config_file))
elif config_commands:
if isinstance(config_commands, (six.string_types, six.text_type)):
config_commands = [config_commands]
file_str = '\n'.join(config_commands)
# unify all the commands in a single file, to render them in a go
if template_engine:
file_str = __salt__['file.apply_template_on_contents'](file_str,
template_engine,
context,
defaults,
saltenv)
# whatever the source of the commands would be, split them line by line
config_commands = [line for line in file_str.splitlines() if line.strip()]
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
conn = __proxy__['netmiko.conn']()
else:
conn, kwargs = _prepare_connection(**kwargs)
if commit:
kwargs['exit_config_mode'] = False # don't exit config mode after
# loading the commands, wait for explicit commit
ret = conn.send_config_set(config_commands=config_commands, **kwargs)
if commit:
ret += conn.commit()
return ret
def commit(**kwargs):
'''
Commit the configuration changes.
.. warning::
This function is supported only on the platforms that support the
``commit`` operation.
CLI Example:
.. code-block:: bash
salt '*' netmiko.commit
'''
return call('commit', **kwargs)
|
saltstack/salt
|
salt/modules/netmiko_mod.py
|
multi_call
|
python
|
def multi_call(*methods, **kwargs):
'''
Invoke multiple Netmiko methods at once, and return their output, as list.
methods
A list of dictionaries with the following keys:
- ``name``: the name of the Netmiko method to be executed.
- ``args``: list of arguments to be sent to the Netmiko method.
- ``kwargs``: dictionary of arguments to be sent to the Netmiko method.
kwargs
Key-value dictionary with the connection details (when not running
under a Proxy Minion).
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
conn = __proxy__['netmiko.conn']()
else:
conn, kwargs = _prepare_connection(**kwargs)
ret = []
for method in methods:
# Explicit unpacking
method_name = method['name']
method_args = method.get('args', [])
method_kwargs = method.get('kwargs', [])
ret.append(getattr(conn, method_name)(*method_args, **method_kwargs))
if 'netmiko.conn' not in __proxy__:
conn.disconnect()
return ret
|
Invoke multiple Netmiko methods at once, and return their output, as list.
methods
A list of dictionaries with the following keys:
- ``name``: the name of the Netmiko method to be executed.
- ``args``: list of arguments to be sent to the Netmiko method.
- ``kwargs``: dictionary of arguments to be sent to the Netmiko method.
kwargs
Key-value dictionary with the connection details (when not running
under a Proxy Minion).
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netmiko_mod.py#L319-L348
|
[
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def _prepare_connection(**kwargs):\n '''\n Prepare the connection with the remote network device, and clean up the key\n value pairs, removing the args used for the connection init.\n '''\n init_args = {}\n fun_kwargs = {}\n netmiko_kwargs = __salt__['config.get']('netmiko', {})\n netmiko_kwargs.update(kwargs) # merge the CLI args with the opts/pillar\n netmiko_init_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)\n check_self = netmiko_init_args.pop(0)\n for karg, warg in six.iteritems(netmiko_kwargs):\n if karg not in netmiko_init_args:\n if warg is not None:\n fun_kwargs[karg] = warg\n continue\n if warg is not None:\n init_args[karg] = warg\n conn = ConnectHandler(**init_args)\n return conn, fun_kwargs\n"
] |
# -*- coding: utf-8 -*-
'''
Netmiko Execution Module
========================
.. versionadded:: 2019.2.0
Execution module to interface the connection with a remote network device. It is
flexible enough to execute the commands both when running under a Netmiko Proxy
Minion, as well as running under a Regular Minion by specifying the connection
arguments, i.e., ``device_type``, ``ip``, ``username``, ``password`` etc.
:codeauthor: Mircea Ulinic <ping@mirceaulinic.net> & Kirk Byers <ktbyers@twb-tech.com>
:maturity: new
:depends: netmiko
:platform: unix
Dependencies
------------
The ``netmiko`` proxy modules requires Netmiko to be installed: ``pip install netmiko``.
Usage
-----
This module can equally be used via the :mod:`netmiko <salt.proxy.netmiko_px>`
Proxy module (check documentation), or directly from an arbitrary (Proxy) Minion
that is running on a server (computer) having access to the network device, and
has the ``netmiko`` library installed.
When running outside of the :mod:`netmiko Proxy <salt.proxy.netmiko_px>` (i.e.,
from another Proxy Minion type, or regular Minion), the netmiko connection
arguments can be either specified from the CLI when executing the command, or
in a configuration block under the ``netmiko`` key in the configuration opts
(i.e., (Proxy) Minion configuration file), or Pillar. The module supports these
simultaneously. These fields are the exact same supported by the ``netmiko``
Proxy Module:
- ``device_type`` - Class selection based on device type. Supported options:
- ``a10``: A10 Networks
- ``accedian``: Accedian Networks
- ``alcatel_aos``: Alcatel AOS
- ``alcatel_sros``: Alcatel SROS
- ``apresia_aeos``: Apresia AEOS
- ``arista_eos``: Arista EOS
- ``aruba_os``: Aruba
- ``avaya_ers``: Avaya ERS
- ``avaya_vsp``: Avaya VSP
- ``brocade_fastiron``: Brocade Fastiron
- ``brocade_netiron``: Brocade Netiron
- ``brocade_nos``: Brocade NOS
- ``brocade_vdx``: Brocade NOS
- ``brocade_vyos``: VyOS
- ``checkpoint_gaia``: Check Point GAiA
- ``calix_b6``: Calix B6
- ``ciena_saos``: Ciena SAOS
- ``cisco_asa``: Cisco SA
- ``cisco_ios``: Cisco IOS
- ``cisco_nxos``: Cisco NX-oS
- ``cisco_s300``: Cisco S300
- ``cisco_tp``: Cisco TpTcCe
- ``cisco_wlc``: Cisco WLC
- ``cisco_xe``: Cisco IOS
- ``cisco_xr``: Cisco XR
- ``coriant``: Coriant
- ``dell_force10``: Dell Force10
- ``dell_os10``: Dell OS10
- ``dell_powerconnect``: Dell PowerConnect
- ``eltex``: Eltex
- ``enterasys``: Enterasys
- ``extreme``: Extreme
- ``extreme_wing``: Extreme Wing
- ``f5_ltm``: F5 LTM
- ``fortinet``: Fortinet
- ``generic_termserver``: TerminalServer
- ``hp_comware``: HP Comware
- ``hp_procurve``: HP Procurve
- ``huawei``: Huawei
- ``huawei_vrpv8``: Huawei VRPV8
- ``juniper``: Juniper Junos
- ``juniper_junos``: Juniper Junos
- ``linux``: Linux
- ``mellanox``: Mellanox
- ``mrv_optiswitch``: MrvOptiswitch
- ``netapp_cdot``: NetAppcDot
- ``netscaler``: Netscaler
- ``ovs_linux``: OvsLinux
- ``paloalto_panos``: PaloAlto Panos
- ``pluribus``: Pluribus
- ``quanta_mesh``: Quanta Mesh
- ``ruckus_fastiron``: Ruckus Fastiron
- ``ubiquiti_edge``: Ubiquiti Edge
- ``ubiquiti_edgeswitch``: Ubiquiti Edge
- ``vyatta_vyos``: VyOS
- ``vyos``: VyOS
- ``brocade_fastiron_telnet``: Brocade Fastiron over Telnet
- ``brocade_netiron_telnet``: Brocade Netiron over Telnet
- ``cisco_ios_telnet``: Cisco IOS over Telnet
- ``apresia_aeos_telnet``: Apresia AEOS over Telnet
- ``arista_eos_telnet``: Arista EOS over Telnet
- ``hp_procurve_telnet``: HP Procurve over Telnet
- ``hp_comware_telnet``: HP Comware over Telnet
- ``juniper_junos_telnet``: Juniper Junos over Telnet
- ``calix_b6_telnet``: Calix B6 over Telnet
- ``dell_powerconnect_telnet``: Dell PowerConnect over Telnet
- ``generic_termserver_telnet``: TerminalServer over Telnet
- ``extreme_telnet``: Extreme Networks over Telnet
- ``ruckus_fastiron_telnet``: Ruckus Fastiron over Telnet
- ``cisco_ios_serial``: Cisco IOS over serial port
- ``ip`` - IP address of target device (not required if ``host`` is provided)
- ``host`` - Hostname of target device (not required if ``ip`` is provided)
- ``username`` - Username to authenticate against target device, if required
- ``password`` - Password to authenticate against target device, if required
- ``secret`` - The enable password if target device requires one
- ``port`` - The destination port used to connect to the target device
- ``global_delay_factor`` - Multiplication factor affecting Netmiko delays
(default: ``1``)
- ``use_keys`` - Connect to target device using SSH keys (default: ``False``)
- ``key_file`` - Filename path of the SSH key file to use
- ``allow_agent`` - Enable use of SSH key-agent
- ``ssh_strict`` - Automatically reject unknown SSH host keys (default:
``False``, which means unknown SSH host keys will be accepted)
- ``system_host_keys`` - Load host keys from the user's "known_hosts" file
(default: ``False``)
- ``alt_host_keys`` - If ``True``, host keys will be loaded from the file
specified in ``alt_key_file`` (default: ``False``)
- ``alt_key_file`` - SSH host key file to use (if ``alt_host_keys=True``)
- ``ssh_config_file`` - File name of OpenSSH configuration file
- ``timeout`` - Connection timeout, in seconds (default: ``90``)
- ``session_timeout`` - Set a timeout for parallel requests, in seconds
(default: ``60``)
- ``keepalive`` - Send SSH keepalive packets at a specific interval, in
seconds. Currently defaults to ``0``, for backwards compatibility (it will
not attempt to keep the connection alive using the KEEPALIVE packets).
- ``default_enter`` - Character(s) to send to correspond to enter key (default:
``\\n``)
- ``response_return`` - Character(s) to use in normalized return data to
represent enter key (default: ``\\n``)
Example (when not running in a ``netmiko`` Proxy Minion):
.. code-block:: yaml
netmiko:
username: test
password: test
In case the ``username`` and ``password`` are the same on any device you are
targeting, the block above (besides other parameters specific to your
environment you might need) should suffice to be able to execute commands from
outside a ``netmiko`` Proxy, e.g.:
.. code-block:: bash
salt '*' netmiko.send_command 'show version' host=router1.example.com device_type=juniper
salt '*' netmiko.send_config https://bit.ly/2sgljCB host=sw2.example.com device_type=cisco_ios
.. note::
Remember that the above applies only when not running in a ``netmiko`` Proxy
Minion. If you want to use the :mod:`<salt.proxy.netmiko_px>`, please follow
the documentation notes for a proper setup.
'''
from __future__ import absolute_import
# Import python stdlib
import logging
import inspect
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
try:
from salt.utils.args import clean_kwargs
except ImportError:
from salt.utils import clean_kwargs
# Import third party libs
try:
from netmiko import ConnectHandler
from netmiko import BaseConnection
HAS_NETMIKO = True
except ImportError:
HAS_NETMIKO = False
# -----------------------------------------------------------------------------
# execution module properties
# -----------------------------------------------------------------------------
__proxyenabled__ = ['*']
# Any Proxy Minion should be able to execute these (not only netmiko)
__virtualname__ = 'netmiko'
# The Execution Module will be identified as ``netmiko``
# -----------------------------------------------------------------------------
# globals
# -----------------------------------------------------------------------------
log = logging.getLogger(__name__)
# -----------------------------------------------------------------------------
# propery functions
# -----------------------------------------------------------------------------
def __virtual__():
'''
Execution module available only if Netmiko is installed.
'''
if not HAS_NETMIKO:
return False, 'The netmiko execution module requires netmiko library to be installed.'
return __virtualname__
# -----------------------------------------------------------------------------
# helper functions
# -----------------------------------------------------------------------------
def _prepare_connection(**kwargs):
'''
Prepare the connection with the remote network device, and clean up the key
value pairs, removing the args used for the connection init.
'''
init_args = {}
fun_kwargs = {}
netmiko_kwargs = __salt__['config.get']('netmiko', {})
netmiko_kwargs.update(kwargs) # merge the CLI args with the opts/pillar
netmiko_init_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)
check_self = netmiko_init_args.pop(0)
for karg, warg in six.iteritems(netmiko_kwargs):
if karg not in netmiko_init_args:
if warg is not None:
fun_kwargs[karg] = warg
continue
if warg is not None:
init_args[karg] = warg
conn = ConnectHandler(**init_args)
return conn, fun_kwargs
# -----------------------------------------------------------------------------
# callable functions
# -----------------------------------------------------------------------------
def get_connection(**kwargs):
'''
Return the Netmiko connection object.
.. warning::
This function returns an unserializable object, hence it is not meant
to be used on the CLI. This should mainly be used when invoked from
other modules for the low level connection with the network device.
kwargs
Key-value dictionary with the authentication details.
USAGE Example:
.. code-block:: python
conn = __salt__['netmiko.get_connection'](host='router1.example.com',
username='example',
password='example')
show_if = conn.send_command('show interfaces')
conn.disconnect()
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
return __proxy__['netmiko.conn']()
conn, kwargs = _prepare_connection(**kwargs)
return conn
def call(method, *args, **kwargs):
'''
Invoke an arbitrary Netmiko method.
method
The name of the Netmiko method to invoke.
args
A list of arguments to send to the method invoked.
kwargs
Key-value dictionary to send to the method invoked.
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.call' in __proxy__:
return __proxy__['netmiko.call'](method, *args, **kwargs)
conn, kwargs = _prepare_connection(**kwargs)
ret = getattr(conn, method)(*args, **kwargs)
conn.disconnect()
return ret
def send_command(command_string, **kwargs):
'''
Execute command_string on the SSH channel using a pattern-based mechanism.
Generally used for show commands. By default this method will keep waiting
to receive data until the network device prompt is detected. The current
network device prompt will be determined automatically.
command_string
The command to be executed on the remote device.
expect_string
Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
auto_find_prompt: ``True``
Whether it should try to auto-detect the prompt (default: ``True``).
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_command 'show version'
salt '*' netmiko.send_command 'show_version' host='router1.example.com' username='example' device_type='cisco_ios'
'''
return call('send_command', command_string, **kwargs)
def send_command_timing(command_string, **kwargs):
'''
Execute command_string on the SSH channel using a delay-based mechanism.
Generally used for show commands.
command_string
The command to be executed on the remote device.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_command_timing 'show version'
salt '*' netmiko.send_command_timing 'show version' host='router1.example.com' username='example' device_type='arista_eos'
'''
return call('send_command_timing', command_string, **kwargs)
def enter_config_mode(**kwargs):
'''
Enter into config mode.
config_command
Configuration command to send to the device.
pattern
Pattern to terminate reading of channel.
CLI Example:
.. code-block:: bash
salt '*' netmiko.enter_config_mode
salt '*' netmiko.enter_config_mode device_type='juniper_junos' ip='192.168.0.1' username='example'
'''
return call('config_mode', **kwargs)
def exit_config_mode(**kwargs):
'''
Exit from configuration mode.
exit_config
Command to exit configuration mode.
pattern
Pattern to terminate reading of channel.
CLI Example:
.. code-block:: bash
salt '*' netmiko.exit_config_mode
salt '*' netmiko.exit_config_mode device_type='juniper' ip='192.168.0.1' username='example'
'''
return call('exit_config_mode', **kwargs)
def send_config(config_file=None,
config_commands=None,
template_engine='jinja',
commit=False,
context=None,
defaults=None,
saltenv='base',
**kwargs):
'''
Send configuration commands down the SSH channel.
Return the configuration lines sent to the device.
The function is flexible to send the configuration from a local or remote
file, or simply the commands as list.
config_file
The source file with the configuration commands to be sent to the
device.
The file can also be a template that can be rendered using the template
engine of choice.
This can be specified using the absolute path to the file, or using one
of the following URL schemes:
- ``salt://``, to fetch the file from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
config_commands
Multiple configuration commands to be sent to the device.
.. note::
This argument is ignored when ``config_file`` is specified.
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
commit: ``False``
Commit the configuration changes before exiting the config mode. This
option is by default disabled, as many platforms don't have this
capability natively.
context
Variables to add to the template context.
defaults
Default values of the context_dict.
exit_config_mode: ``True``
Determines whether or not to exit config mode after complete.
delay_factor: ``1``
Factor to adjust delays.
max_loops: ``150``
Controls wait time in conjunction with delay_factor (default: ``150``).
strip_prompt: ``False``
Determines whether or not to strip the prompt (default: ``False``).
strip_command: ``False``
Determines whether or not to strip the command (default: ``False``).
config_mode_command
The command to enter into config mode.
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_config config_commands="['interface GigabitEthernet3', 'no ip address']"
salt '*' netmiko.send_config config_commands="['snmp-server location {{ grains.location }}']"
salt '*' netmiko.send_config config_file=salt://config.txt
salt '*' netmiko.send_config config_file=https://bit.ly/2sgljCB device_type='cisco_ios' ip='1.2.3.4' username='example'
'''
if config_file:
file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv)
if file_str is False:
raise CommandExecutionError('Source file {} not found'.format(config_file))
elif config_commands:
if isinstance(config_commands, (six.string_types, six.text_type)):
config_commands = [config_commands]
file_str = '\n'.join(config_commands)
# unify all the commands in a single file, to render them in a go
if template_engine:
file_str = __salt__['file.apply_template_on_contents'](file_str,
template_engine,
context,
defaults,
saltenv)
# whatever the source of the commands would be, split them line by line
config_commands = [line for line in file_str.splitlines() if line.strip()]
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
conn = __proxy__['netmiko.conn']()
else:
conn, kwargs = _prepare_connection(**kwargs)
if commit:
kwargs['exit_config_mode'] = False # don't exit config mode after
# loading the commands, wait for explicit commit
ret = conn.send_config_set(config_commands=config_commands, **kwargs)
if commit:
ret += conn.commit()
return ret
def commit(**kwargs):
'''
Commit the configuration changes.
.. warning::
This function is supported only on the platforms that support the
``commit`` operation.
CLI Example:
.. code-block:: bash
salt '*' netmiko.commit
'''
return call('commit', **kwargs)
|
saltstack/salt
|
salt/modules/netmiko_mod.py
|
send_config
|
python
|
def send_config(config_file=None,
config_commands=None,
template_engine='jinja',
commit=False,
context=None,
defaults=None,
saltenv='base',
**kwargs):
'''
Send configuration commands down the SSH channel.
Return the configuration lines sent to the device.
The function is flexible to send the configuration from a local or remote
file, or simply the commands as list.
config_file
The source file with the configuration commands to be sent to the
device.
The file can also be a template that can be rendered using the template
engine of choice.
This can be specified using the absolute path to the file, or using one
of the following URL schemes:
- ``salt://``, to fetch the file from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
config_commands
Multiple configuration commands to be sent to the device.
.. note::
This argument is ignored when ``config_file`` is specified.
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
commit: ``False``
Commit the configuration changes before exiting the config mode. This
option is by default disabled, as many platforms don't have this
capability natively.
context
Variables to add to the template context.
defaults
Default values of the context_dict.
exit_config_mode: ``True``
Determines whether or not to exit config mode after complete.
delay_factor: ``1``
Factor to adjust delays.
max_loops: ``150``
Controls wait time in conjunction with delay_factor (default: ``150``).
strip_prompt: ``False``
Determines whether or not to strip the prompt (default: ``False``).
strip_command: ``False``
Determines whether or not to strip the command (default: ``False``).
config_mode_command
The command to enter into config mode.
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_config config_commands="['interface GigabitEthernet3', 'no ip address']"
salt '*' netmiko.send_config config_commands="['snmp-server location {{ grains.location }}']"
salt '*' netmiko.send_config config_file=salt://config.txt
salt '*' netmiko.send_config config_file=https://bit.ly/2sgljCB device_type='cisco_ios' ip='1.2.3.4' username='example'
'''
if config_file:
file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv)
if file_str is False:
raise CommandExecutionError('Source file {} not found'.format(config_file))
elif config_commands:
if isinstance(config_commands, (six.string_types, six.text_type)):
config_commands = [config_commands]
file_str = '\n'.join(config_commands)
# unify all the commands in a single file, to render them in a go
if template_engine:
file_str = __salt__['file.apply_template_on_contents'](file_str,
template_engine,
context,
defaults,
saltenv)
# whatever the source of the commands would be, split them line by line
config_commands = [line for line in file_str.splitlines() if line.strip()]
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
conn = __proxy__['netmiko.conn']()
else:
conn, kwargs = _prepare_connection(**kwargs)
if commit:
kwargs['exit_config_mode'] = False # don't exit config mode after
# loading the commands, wait for explicit commit
ret = conn.send_config_set(config_commands=config_commands, **kwargs)
if commit:
ret += conn.commit()
return ret
|
Send configuration commands down the SSH channel.
Return the configuration lines sent to the device.
The function is flexible to send the configuration from a local or remote
file, or simply the commands as list.
config_file
The source file with the configuration commands to be sent to the
device.
The file can also be a template that can be rendered using the template
engine of choice.
This can be specified using the absolute path to the file, or using one
of the following URL schemes:
- ``salt://``, to fetch the file from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
config_commands
Multiple configuration commands to be sent to the device.
.. note::
This argument is ignored when ``config_file`` is specified.
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
commit: ``False``
Commit the configuration changes before exiting the config mode. This
option is by default disabled, as many platforms don't have this
capability natively.
context
Variables to add to the template context.
defaults
Default values of the context_dict.
exit_config_mode: ``True``
Determines whether or not to exit config mode after complete.
delay_factor: ``1``
Factor to adjust delays.
max_loops: ``150``
Controls wait time in conjunction with delay_factor (default: ``150``).
strip_prompt: ``False``
Determines whether or not to strip the prompt (default: ``False``).
strip_command: ``False``
Determines whether or not to strip the command (default: ``False``).
config_mode_command
The command to enter into config mode.
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_config config_commands="['interface GigabitEthernet3', 'no ip address']"
salt '*' netmiko.send_config config_commands="['snmp-server location {{ grains.location }}']"
salt '*' netmiko.send_config config_file=salt://config.txt
salt '*' netmiko.send_config config_file=https://bit.ly/2sgljCB device_type='cisco_ios' ip='1.2.3.4' username='example'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netmiko_mod.py#L474-L583
|
[
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def _prepare_connection(**kwargs):\n '''\n Prepare the connection with the remote network device, and clean up the key\n value pairs, removing the args used for the connection init.\n '''\n init_args = {}\n fun_kwargs = {}\n netmiko_kwargs = __salt__['config.get']('netmiko', {})\n netmiko_kwargs.update(kwargs) # merge the CLI args with the opts/pillar\n netmiko_init_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)\n check_self = netmiko_init_args.pop(0)\n for karg, warg in six.iteritems(netmiko_kwargs):\n if karg not in netmiko_init_args:\n if warg is not None:\n fun_kwargs[karg] = warg\n continue\n if warg is not None:\n init_args[karg] = warg\n conn = ConnectHandler(**init_args)\n return conn, fun_kwargs\n"
] |
# -*- coding: utf-8 -*-
'''
Netmiko Execution Module
========================
.. versionadded:: 2019.2.0
Execution module to interface the connection with a remote network device. It is
flexible enough to execute the commands both when running under a Netmiko Proxy
Minion, as well as running under a Regular Minion by specifying the connection
arguments, i.e., ``device_type``, ``ip``, ``username``, ``password`` etc.
:codeauthor: Mircea Ulinic <ping@mirceaulinic.net> & Kirk Byers <ktbyers@twb-tech.com>
:maturity: new
:depends: netmiko
:platform: unix
Dependencies
------------
The ``netmiko`` proxy modules requires Netmiko to be installed: ``pip install netmiko``.
Usage
-----
This module can equally be used via the :mod:`netmiko <salt.proxy.netmiko_px>`
Proxy module (check documentation), or directly from an arbitrary (Proxy) Minion
that is running on a server (computer) having access to the network device, and
has the ``netmiko`` library installed.
When running outside of the :mod:`netmiko Proxy <salt.proxy.netmiko_px>` (i.e.,
from another Proxy Minion type, or regular Minion), the netmiko connection
arguments can be either specified from the CLI when executing the command, or
in a configuration block under the ``netmiko`` key in the configuration opts
(i.e., (Proxy) Minion configuration file), or Pillar. The module supports these
simultaneously. These fields are the exact same supported by the ``netmiko``
Proxy Module:
- ``device_type`` - Class selection based on device type. Supported options:
- ``a10``: A10 Networks
- ``accedian``: Accedian Networks
- ``alcatel_aos``: Alcatel AOS
- ``alcatel_sros``: Alcatel SROS
- ``apresia_aeos``: Apresia AEOS
- ``arista_eos``: Arista EOS
- ``aruba_os``: Aruba
- ``avaya_ers``: Avaya ERS
- ``avaya_vsp``: Avaya VSP
- ``brocade_fastiron``: Brocade Fastiron
- ``brocade_netiron``: Brocade Netiron
- ``brocade_nos``: Brocade NOS
- ``brocade_vdx``: Brocade NOS
- ``brocade_vyos``: VyOS
- ``checkpoint_gaia``: Check Point GAiA
- ``calix_b6``: Calix B6
- ``ciena_saos``: Ciena SAOS
- ``cisco_asa``: Cisco SA
- ``cisco_ios``: Cisco IOS
- ``cisco_nxos``: Cisco NX-oS
- ``cisco_s300``: Cisco S300
- ``cisco_tp``: Cisco TpTcCe
- ``cisco_wlc``: Cisco WLC
- ``cisco_xe``: Cisco IOS
- ``cisco_xr``: Cisco XR
- ``coriant``: Coriant
- ``dell_force10``: Dell Force10
- ``dell_os10``: Dell OS10
- ``dell_powerconnect``: Dell PowerConnect
- ``eltex``: Eltex
- ``enterasys``: Enterasys
- ``extreme``: Extreme
- ``extreme_wing``: Extreme Wing
- ``f5_ltm``: F5 LTM
- ``fortinet``: Fortinet
- ``generic_termserver``: TerminalServer
- ``hp_comware``: HP Comware
- ``hp_procurve``: HP Procurve
- ``huawei``: Huawei
- ``huawei_vrpv8``: Huawei VRPV8
- ``juniper``: Juniper Junos
- ``juniper_junos``: Juniper Junos
- ``linux``: Linux
- ``mellanox``: Mellanox
- ``mrv_optiswitch``: MrvOptiswitch
- ``netapp_cdot``: NetAppcDot
- ``netscaler``: Netscaler
- ``ovs_linux``: OvsLinux
- ``paloalto_panos``: PaloAlto Panos
- ``pluribus``: Pluribus
- ``quanta_mesh``: Quanta Mesh
- ``ruckus_fastiron``: Ruckus Fastiron
- ``ubiquiti_edge``: Ubiquiti Edge
- ``ubiquiti_edgeswitch``: Ubiquiti Edge
- ``vyatta_vyos``: VyOS
- ``vyos``: VyOS
- ``brocade_fastiron_telnet``: Brocade Fastiron over Telnet
- ``brocade_netiron_telnet``: Brocade Netiron over Telnet
- ``cisco_ios_telnet``: Cisco IOS over Telnet
- ``apresia_aeos_telnet``: Apresia AEOS over Telnet
- ``arista_eos_telnet``: Arista EOS over Telnet
- ``hp_procurve_telnet``: HP Procurve over Telnet
- ``hp_comware_telnet``: HP Comware over Telnet
- ``juniper_junos_telnet``: Juniper Junos over Telnet
- ``calix_b6_telnet``: Calix B6 over Telnet
- ``dell_powerconnect_telnet``: Dell PowerConnect over Telnet
- ``generic_termserver_telnet``: TerminalServer over Telnet
- ``extreme_telnet``: Extreme Networks over Telnet
- ``ruckus_fastiron_telnet``: Ruckus Fastiron over Telnet
- ``cisco_ios_serial``: Cisco IOS over serial port
- ``ip`` - IP address of target device (not required if ``host`` is provided)
- ``host`` - Hostname of target device (not required if ``ip`` is provided)
- ``username`` - Username to authenticate against target device, if required
- ``password`` - Password to authenticate against target device, if required
- ``secret`` - The enable password if target device requires one
- ``port`` - The destination port used to connect to the target device
- ``global_delay_factor`` - Multiplication factor affecting Netmiko delays
(default: ``1``)
- ``use_keys`` - Connect to target device using SSH keys (default: ``False``)
- ``key_file`` - Filename path of the SSH key file to use
- ``allow_agent`` - Enable use of SSH key-agent
- ``ssh_strict`` - Automatically reject unknown SSH host keys (default:
``False``, which means unknown SSH host keys will be accepted)
- ``system_host_keys`` - Load host keys from the user's "known_hosts" file
(default: ``False``)
- ``alt_host_keys`` - If ``True``, host keys will be loaded from the file
specified in ``alt_key_file`` (default: ``False``)
- ``alt_key_file`` - SSH host key file to use (if ``alt_host_keys=True``)
- ``ssh_config_file`` - File name of OpenSSH configuration file
- ``timeout`` - Connection timeout, in seconds (default: ``90``)
- ``session_timeout`` - Set a timeout for parallel requests, in seconds
(default: ``60``)
- ``keepalive`` - Send SSH keepalive packets at a specific interval, in
seconds. Currently defaults to ``0``, for backwards compatibility (it will
not attempt to keep the connection alive using the KEEPALIVE packets).
- ``default_enter`` - Character(s) to send to correspond to enter key (default:
``\\n``)
- ``response_return`` - Character(s) to use in normalized return data to
represent enter key (default: ``\\n``)
Example (when not running in a ``netmiko`` Proxy Minion):
.. code-block:: yaml
netmiko:
username: test
password: test
In case the ``username`` and ``password`` are the same on any device you are
targeting, the block above (besides other parameters specific to your
environment you might need) should suffice to be able to execute commands from
outside a ``netmiko`` Proxy, e.g.:
.. code-block:: bash
salt '*' netmiko.send_command 'show version' host=router1.example.com device_type=juniper
salt '*' netmiko.send_config https://bit.ly/2sgljCB host=sw2.example.com device_type=cisco_ios
.. note::
Remember that the above applies only when not running in a ``netmiko`` Proxy
Minion. If you want to use the :mod:`<salt.proxy.netmiko_px>`, please follow
the documentation notes for a proper setup.
'''
from __future__ import absolute_import
# Import python stdlib
import logging
import inspect
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
try:
from salt.utils.args import clean_kwargs
except ImportError:
from salt.utils import clean_kwargs
# Import third party libs
try:
from netmiko import ConnectHandler
from netmiko import BaseConnection
HAS_NETMIKO = True
except ImportError:
HAS_NETMIKO = False
# -----------------------------------------------------------------------------
# execution module properties
# -----------------------------------------------------------------------------
__proxyenabled__ = ['*']
# Any Proxy Minion should be able to execute these (not only netmiko)
__virtualname__ = 'netmiko'
# The Execution Module will be identified as ``netmiko``
# -----------------------------------------------------------------------------
# globals
# -----------------------------------------------------------------------------
log = logging.getLogger(__name__)
# -----------------------------------------------------------------------------
# propery functions
# -----------------------------------------------------------------------------
def __virtual__():
'''
Execution module available only if Netmiko is installed.
'''
if not HAS_NETMIKO:
return False, 'The netmiko execution module requires netmiko library to be installed.'
return __virtualname__
# -----------------------------------------------------------------------------
# helper functions
# -----------------------------------------------------------------------------
def _prepare_connection(**kwargs):
'''
Prepare the connection with the remote network device, and clean up the key
value pairs, removing the args used for the connection init.
'''
init_args = {}
fun_kwargs = {}
netmiko_kwargs = __salt__['config.get']('netmiko', {})
netmiko_kwargs.update(kwargs) # merge the CLI args with the opts/pillar
netmiko_init_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)
check_self = netmiko_init_args.pop(0)
for karg, warg in six.iteritems(netmiko_kwargs):
if karg not in netmiko_init_args:
if warg is not None:
fun_kwargs[karg] = warg
continue
if warg is not None:
init_args[karg] = warg
conn = ConnectHandler(**init_args)
return conn, fun_kwargs
# -----------------------------------------------------------------------------
# callable functions
# -----------------------------------------------------------------------------
def get_connection(**kwargs):
'''
Return the Netmiko connection object.
.. warning::
This function returns an unserializable object, hence it is not meant
to be used on the CLI. This should mainly be used when invoked from
other modules for the low level connection with the network device.
kwargs
Key-value dictionary with the authentication details.
USAGE Example:
.. code-block:: python
conn = __salt__['netmiko.get_connection'](host='router1.example.com',
username='example',
password='example')
show_if = conn.send_command('show interfaces')
conn.disconnect()
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
return __proxy__['netmiko.conn']()
conn, kwargs = _prepare_connection(**kwargs)
return conn
def call(method, *args, **kwargs):
'''
Invoke an arbitrary Netmiko method.
method
The name of the Netmiko method to invoke.
args
A list of arguments to send to the method invoked.
kwargs
Key-value dictionary to send to the method invoked.
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.call' in __proxy__:
return __proxy__['netmiko.call'](method, *args, **kwargs)
conn, kwargs = _prepare_connection(**kwargs)
ret = getattr(conn, method)(*args, **kwargs)
conn.disconnect()
return ret
def multi_call(*methods, **kwargs):
'''
Invoke multiple Netmiko methods at once, and return their output, as list.
methods
A list of dictionaries with the following keys:
- ``name``: the name of the Netmiko method to be executed.
- ``args``: list of arguments to be sent to the Netmiko method.
- ``kwargs``: dictionary of arguments to be sent to the Netmiko method.
kwargs
Key-value dictionary with the connection details (when not running
under a Proxy Minion).
'''
kwargs = clean_kwargs(**kwargs)
if 'netmiko.conn' in __proxy__:
conn = __proxy__['netmiko.conn']()
else:
conn, kwargs = _prepare_connection(**kwargs)
ret = []
for method in methods:
# Explicit unpacking
method_name = method['name']
method_args = method.get('args', [])
method_kwargs = method.get('kwargs', [])
ret.append(getattr(conn, method_name)(*method_args, **method_kwargs))
if 'netmiko.conn' not in __proxy__:
conn.disconnect()
return ret
def send_command(command_string, **kwargs):
'''
Execute command_string on the SSH channel using a pattern-based mechanism.
Generally used for show commands. By default this method will keep waiting
to receive data until the network device prompt is detected. The current
network device prompt will be determined automatically.
command_string
The command to be executed on the remote device.
expect_string
Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
auto_find_prompt: ``True``
Whether it should try to auto-detect the prompt (default: ``True``).
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_command 'show version'
salt '*' netmiko.send_command 'show_version' host='router1.example.com' username='example' device_type='cisco_ios'
'''
return call('send_command', command_string, **kwargs)
def send_command_timing(command_string, **kwargs):
'''
Execute command_string on the SSH channel using a delay-based mechanism.
Generally used for show commands.
command_string
The command to be executed on the remote device.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' netmiko.send_command_timing 'show version'
salt '*' netmiko.send_command_timing 'show version' host='router1.example.com' username='example' device_type='arista_eos'
'''
return call('send_command_timing', command_string, **kwargs)
def enter_config_mode(**kwargs):
'''
Enter into config mode.
config_command
Configuration command to send to the device.
pattern
Pattern to terminate reading of channel.
CLI Example:
.. code-block:: bash
salt '*' netmiko.enter_config_mode
salt '*' netmiko.enter_config_mode device_type='juniper_junos' ip='192.168.0.1' username='example'
'''
return call('config_mode', **kwargs)
def exit_config_mode(**kwargs):
'''
Exit from configuration mode.
exit_config
Command to exit configuration mode.
pattern
Pattern to terminate reading of channel.
CLI Example:
.. code-block:: bash
salt '*' netmiko.exit_config_mode
salt '*' netmiko.exit_config_mode device_type='juniper' ip='192.168.0.1' username='example'
'''
return call('exit_config_mode', **kwargs)
def commit(**kwargs):
'''
Commit the configuration changes.
.. warning::
This function is supported only on the platforms that support the
``commit`` operation.
CLI Example:
.. code-block:: bash
salt '*' netmiko.commit
'''
return call('commit', **kwargs)
|
saltstack/salt
|
salt/modules/qemu_nbd.py
|
connect
|
python
|
def connect(image):
'''
Activate nbd for an image file.
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.connect /tmp/image.raw
'''
if not os.path.isfile(image):
log.warning('Could not connect image: %s does not exist', image)
return ''
if salt.utils.path.which('sfdisk'):
fdisk = 'sfdisk -d'
else:
fdisk = 'fdisk -l'
__salt__['cmd.run']('modprobe nbd max_part=63')
for nbd in glob.glob('/dev/nbd?'):
if __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):
while True:
# Sometimes nbd does not "take hold", loop until we can verify
__salt__['cmd.run'](
'qemu-nbd -c {0} {1}'.format(nbd, image),
python_shell=False,
)
if not __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):
break
return nbd
log.warning('Could not connect image: %s', image)
return ''
|
Activate nbd for an image file.
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.connect /tmp/image.raw
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/qemu_nbd.py#L37-L68
| null |
# -*- coding: utf-8 -*-
'''
Qemu Command Wrapper
The qemu system comes with powerful tools, such as qemu-img and qemu-nbd which
are used here to build up kvm images.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import glob
import tempfile
import time
import logging
# Import salt libs
import salt.utils.path
import salt.crypt
# Import 3rd-party libs
from salt.ext import six
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if qemu-img and qemu-nbd are installed
'''
if salt.utils.path.which('qemu-nbd'):
return 'qemu_nbd'
return (False, 'The qemu_nbd execution module cannot be loaded: the qemu-nbd binary is not in the path.')
def mount(nbd, root=None):
'''
Pass in the nbd connection device location, mount all partitions and return
a dict of mount points
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.mount /dev/nbd0
'''
__salt__['cmd.run'](
'partprobe {0}'.format(nbd),
python_shell=False,
)
ret = {}
if root is None:
root = os.path.join(
tempfile.gettempdir(),
'nbd',
os.path.basename(nbd)
)
for part in glob.glob('{0}p*'.format(nbd)):
m_pt = os.path.join(root, os.path.basename(part))
time.sleep(1)
mnt = __salt__['mount.mount'](m_pt, part, True)
if mnt is not True:
continue
ret[m_pt] = part
return ret
def init(image, root=None):
'''
Mount the named image via qemu-nbd and return the mounted roots
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.init /srv/image.qcow2
'''
nbd = connect(image)
if not nbd:
return ''
return mount(nbd, root)
def clear(mnt):
'''
Pass in the mnt dict returned from nbd_mount to unmount and disconnect
the image from nbd. If all of the partitions are unmounted return an
empty dict, otherwise return a dict containing the still mounted
partitions
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.clear '{"/mnt/foo": "/dev/nbd0p1"}'
'''
ret = {}
nbds = set()
for m_pt, dev in six.iteritems(mnt):
mnt_ret = __salt__['mount.umount'](m_pt)
if mnt_ret is not True:
ret[m_pt] = dev
nbds.add(dev[:dev.rindex('p')])
if ret:
return ret
for nbd in nbds:
__salt__['cmd.run']('qemu-nbd -d {0}'.format(nbd), python_shell=False)
return ret
|
saltstack/salt
|
salt/modules/qemu_nbd.py
|
mount
|
python
|
def mount(nbd, root=None):
'''
Pass in the nbd connection device location, mount all partitions and return
a dict of mount points
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.mount /dev/nbd0
'''
__salt__['cmd.run'](
'partprobe {0}'.format(nbd),
python_shell=False,
)
ret = {}
if root is None:
root = os.path.join(
tempfile.gettempdir(),
'nbd',
os.path.basename(nbd)
)
for part in glob.glob('{0}p*'.format(nbd)):
m_pt = os.path.join(root, os.path.basename(part))
time.sleep(1)
mnt = __salt__['mount.mount'](m_pt, part, True)
if mnt is not True:
continue
ret[m_pt] = part
return ret
|
Pass in the nbd connection device location, mount all partitions and return
a dict of mount points
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.mount /dev/nbd0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/qemu_nbd.py#L71-L100
| null |
# -*- coding: utf-8 -*-
'''
Qemu Command Wrapper
The qemu system comes with powerful tools, such as qemu-img and qemu-nbd which
are used here to build up kvm images.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import glob
import tempfile
import time
import logging
# Import salt libs
import salt.utils.path
import salt.crypt
# Import 3rd-party libs
from salt.ext import six
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if qemu-img and qemu-nbd are installed
'''
if salt.utils.path.which('qemu-nbd'):
return 'qemu_nbd'
return (False, 'The qemu_nbd execution module cannot be loaded: the qemu-nbd binary is not in the path.')
def connect(image):
'''
Activate nbd for an image file.
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.connect /tmp/image.raw
'''
if not os.path.isfile(image):
log.warning('Could not connect image: %s does not exist', image)
return ''
if salt.utils.path.which('sfdisk'):
fdisk = 'sfdisk -d'
else:
fdisk = 'fdisk -l'
__salt__['cmd.run']('modprobe nbd max_part=63')
for nbd in glob.glob('/dev/nbd?'):
if __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):
while True:
# Sometimes nbd does not "take hold", loop until we can verify
__salt__['cmd.run'](
'qemu-nbd -c {0} {1}'.format(nbd, image),
python_shell=False,
)
if not __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):
break
return nbd
log.warning('Could not connect image: %s', image)
return ''
def init(image, root=None):
'''
Mount the named image via qemu-nbd and return the mounted roots
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.init /srv/image.qcow2
'''
nbd = connect(image)
if not nbd:
return ''
return mount(nbd, root)
def clear(mnt):
'''
Pass in the mnt dict returned from nbd_mount to unmount and disconnect
the image from nbd. If all of the partitions are unmounted return an
empty dict, otherwise return a dict containing the still mounted
partitions
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.clear '{"/mnt/foo": "/dev/nbd0p1"}'
'''
ret = {}
nbds = set()
for m_pt, dev in six.iteritems(mnt):
mnt_ret = __salt__['mount.umount'](m_pt)
if mnt_ret is not True:
ret[m_pt] = dev
nbds.add(dev[:dev.rindex('p')])
if ret:
return ret
for nbd in nbds:
__salt__['cmd.run']('qemu-nbd -d {0}'.format(nbd), python_shell=False)
return ret
|
saltstack/salt
|
salt/modules/qemu_nbd.py
|
init
|
python
|
def init(image, root=None):
'''
Mount the named image via qemu-nbd and return the mounted roots
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.init /srv/image.qcow2
'''
nbd = connect(image)
if not nbd:
return ''
return mount(nbd, root)
|
Mount the named image via qemu-nbd and return the mounted roots
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.init /srv/image.qcow2
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/qemu_nbd.py#L103-L116
|
[
"def connect(image):\n '''\n Activate nbd for an image file.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' qemu_nbd.connect /tmp/image.raw\n '''\n if not os.path.isfile(image):\n log.warning('Could not connect image: %s does not exist', image)\n return ''\n\n if salt.utils.path.which('sfdisk'):\n fdisk = 'sfdisk -d'\n else:\n fdisk = 'fdisk -l'\n __salt__['cmd.run']('modprobe nbd max_part=63')\n for nbd in glob.glob('/dev/nbd?'):\n if __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):\n while True:\n # Sometimes nbd does not \"take hold\", loop until we can verify\n __salt__['cmd.run'](\n 'qemu-nbd -c {0} {1}'.format(nbd, image),\n python_shell=False,\n )\n if not __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):\n break\n return nbd\n log.warning('Could not connect image: %s', image)\n return ''\n",
"def mount(nbd, root=None):\n '''\n Pass in the nbd connection device location, mount all partitions and return\n a dict of mount points\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' qemu_nbd.mount /dev/nbd0\n '''\n __salt__['cmd.run'](\n 'partprobe {0}'.format(nbd),\n python_shell=False,\n )\n ret = {}\n if root is None:\n root = os.path.join(\n tempfile.gettempdir(),\n 'nbd',\n os.path.basename(nbd)\n )\n for part in glob.glob('{0}p*'.format(nbd)):\n m_pt = os.path.join(root, os.path.basename(part))\n time.sleep(1)\n mnt = __salt__['mount.mount'](m_pt, part, True)\n if mnt is not True:\n continue\n ret[m_pt] = part\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Qemu Command Wrapper
The qemu system comes with powerful tools, such as qemu-img and qemu-nbd which
are used here to build up kvm images.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import glob
import tempfile
import time
import logging
# Import salt libs
import salt.utils.path
import salt.crypt
# Import 3rd-party libs
from salt.ext import six
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if qemu-img and qemu-nbd are installed
'''
if salt.utils.path.which('qemu-nbd'):
return 'qemu_nbd'
return (False, 'The qemu_nbd execution module cannot be loaded: the qemu-nbd binary is not in the path.')
def connect(image):
'''
Activate nbd for an image file.
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.connect /tmp/image.raw
'''
if not os.path.isfile(image):
log.warning('Could not connect image: %s does not exist', image)
return ''
if salt.utils.path.which('sfdisk'):
fdisk = 'sfdisk -d'
else:
fdisk = 'fdisk -l'
__salt__['cmd.run']('modprobe nbd max_part=63')
for nbd in glob.glob('/dev/nbd?'):
if __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):
while True:
# Sometimes nbd does not "take hold", loop until we can verify
__salt__['cmd.run'](
'qemu-nbd -c {0} {1}'.format(nbd, image),
python_shell=False,
)
if not __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):
break
return nbd
log.warning('Could not connect image: %s', image)
return ''
def mount(nbd, root=None):
'''
Pass in the nbd connection device location, mount all partitions and return
a dict of mount points
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.mount /dev/nbd0
'''
__salt__['cmd.run'](
'partprobe {0}'.format(nbd),
python_shell=False,
)
ret = {}
if root is None:
root = os.path.join(
tempfile.gettempdir(),
'nbd',
os.path.basename(nbd)
)
for part in glob.glob('{0}p*'.format(nbd)):
m_pt = os.path.join(root, os.path.basename(part))
time.sleep(1)
mnt = __salt__['mount.mount'](m_pt, part, True)
if mnt is not True:
continue
ret[m_pt] = part
return ret
def clear(mnt):
'''
Pass in the mnt dict returned from nbd_mount to unmount and disconnect
the image from nbd. If all of the partitions are unmounted return an
empty dict, otherwise return a dict containing the still mounted
partitions
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.clear '{"/mnt/foo": "/dev/nbd0p1"}'
'''
ret = {}
nbds = set()
for m_pt, dev in six.iteritems(mnt):
mnt_ret = __salt__['mount.umount'](m_pt)
if mnt_ret is not True:
ret[m_pt] = dev
nbds.add(dev[:dev.rindex('p')])
if ret:
return ret
for nbd in nbds:
__salt__['cmd.run']('qemu-nbd -d {0}'.format(nbd), python_shell=False)
return ret
|
saltstack/salt
|
salt/modules/qemu_nbd.py
|
clear
|
python
|
def clear(mnt):
'''
Pass in the mnt dict returned from nbd_mount to unmount and disconnect
the image from nbd. If all of the partitions are unmounted return an
empty dict, otherwise return a dict containing the still mounted
partitions
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.clear '{"/mnt/foo": "/dev/nbd0p1"}'
'''
ret = {}
nbds = set()
for m_pt, dev in six.iteritems(mnt):
mnt_ret = __salt__['mount.umount'](m_pt)
if mnt_ret is not True:
ret[m_pt] = dev
nbds.add(dev[:dev.rindex('p')])
if ret:
return ret
for nbd in nbds:
__salt__['cmd.run']('qemu-nbd -d {0}'.format(nbd), python_shell=False)
return ret
|
Pass in the mnt dict returned from nbd_mount to unmount and disconnect
the image from nbd. If all of the partitions are unmounted return an
empty dict, otherwise return a dict containing the still mounted
partitions
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.clear '{"/mnt/foo": "/dev/nbd0p1"}'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/qemu_nbd.py#L119-L143
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Qemu Command Wrapper
The qemu system comes with powerful tools, such as qemu-img and qemu-nbd which
are used here to build up kvm images.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import glob
import tempfile
import time
import logging
# Import salt libs
import salt.utils.path
import salt.crypt
# Import 3rd-party libs
from salt.ext import six
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if qemu-img and qemu-nbd are installed
'''
if salt.utils.path.which('qemu-nbd'):
return 'qemu_nbd'
return (False, 'The qemu_nbd execution module cannot be loaded: the qemu-nbd binary is not in the path.')
def connect(image):
'''
Activate nbd for an image file.
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.connect /tmp/image.raw
'''
if not os.path.isfile(image):
log.warning('Could not connect image: %s does not exist', image)
return ''
if salt.utils.path.which('sfdisk'):
fdisk = 'sfdisk -d'
else:
fdisk = 'fdisk -l'
__salt__['cmd.run']('modprobe nbd max_part=63')
for nbd in glob.glob('/dev/nbd?'):
if __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):
while True:
# Sometimes nbd does not "take hold", loop until we can verify
__salt__['cmd.run'](
'qemu-nbd -c {0} {1}'.format(nbd, image),
python_shell=False,
)
if not __salt__['cmd.retcode']('{0} {1}'.format(fdisk, nbd)):
break
return nbd
log.warning('Could not connect image: %s', image)
return ''
def mount(nbd, root=None):
'''
Pass in the nbd connection device location, mount all partitions and return
a dict of mount points
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.mount /dev/nbd0
'''
__salt__['cmd.run'](
'partprobe {0}'.format(nbd),
python_shell=False,
)
ret = {}
if root is None:
root = os.path.join(
tempfile.gettempdir(),
'nbd',
os.path.basename(nbd)
)
for part in glob.glob('{0}p*'.format(nbd)):
m_pt = os.path.join(root, os.path.basename(part))
time.sleep(1)
mnt = __salt__['mount.mount'](m_pt, part, True)
if mnt is not True:
continue
ret[m_pt] = part
return ret
def init(image, root=None):
'''
Mount the named image via qemu-nbd and return the mounted roots
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.init /srv/image.qcow2
'''
nbd = connect(image)
if not nbd:
return ''
return mount(nbd, root)
|
saltstack/salt
|
salt/scripts.py
|
_handle_interrupt
|
python
|
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
|
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L28-L43
| null |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_master
|
python
|
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
|
Start the salt master.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L100-L116
|
[
"def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
minion_process
|
python
|
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
|
Start a minion process
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L119-L178
|
[
"def appendproctitle(name):\n '''\n Append \"name\" to the current process title\n '''\n if HAS_SETPROCTITLE:\n setproctitle.setproctitle(setproctitle.getproctitle() + ' ' + name)\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_minion
|
python
|
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
|
Start the salt minion in a subprocess.
Auto restart minion on error.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L181-L266
|
[
"def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n",
"def notify_systemd():\n '''\n Notify systemd that this process has started\n '''\n try:\n import systemd.daemon\n except ImportError:\n if salt.utils.path.which('systemd-notify') \\\n and systemd_notify_call('--booted'):\n # Notify systemd synchronously\n notify_socket = os.getenv('NOTIFY_SOCKET')\n if notify_socket:\n # Handle abstract namespace socket\n if notify_socket.startswith('@'):\n notify_socket = '\\0{0}'.format(notify_socket[1:])\n try:\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)\n sock.connect(notify_socket)\n sock.sendall('READY=1'.encode())\n sock.close()\n except socket.error:\n return systemd_notify_call('--ready')\n return True\n return False\n\n if systemd.daemon.booted():\n try:\n return systemd.daemon.notify('READY=1')\n except SystemError:\n # Daemon was not started by systemd\n pass\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
proxy_minion_process
|
python
|
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
|
Start a proxy minion process
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L269-L330
| null |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_proxy
|
python
|
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
|
Start a proxy minion.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L333-L386
| null |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_syndic
|
python
|
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
|
Start the salt syndic.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L389-L402
|
[
"def notify_systemd():\n '''\n Notify systemd that this process has started\n '''\n try:\n import systemd.daemon\n except ImportError:\n if salt.utils.path.which('systemd-notify') \\\n and systemd_notify_call('--booted'):\n # Notify systemd synchronously\n notify_socket = os.getenv('NOTIFY_SOCKET')\n if notify_socket:\n # Handle abstract namespace socket\n if notify_socket.startswith('@'):\n notify_socket = '\\0{0}'.format(notify_socket[1:])\n try:\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)\n sock.connect(notify_socket)\n sock.sendall('READY=1'.encode())\n sock.close()\n except socket.error:\n return systemd_notify_call('--ready')\n return True\n return False\n\n if systemd.daemon.booted():\n try:\n return systemd.daemon.notify('READY=1')\n except SystemError:\n # Daemon was not started by systemd\n pass\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_key
|
python
|
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
|
Manage the authentication keys with salt-key.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L405-L415
|
[
"def _install_signal_handlers(client):\n # Install the SIGINT/SIGTERM handlers if not done so far\n if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n\n if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_cp
|
python
|
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
|
Publish commands to the salt system from the command line on the
master.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L418-L426
|
[
"def _install_signal_handlers(client):\n # Install the SIGINT/SIGTERM handlers if not done so far\n if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n\n if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_call
|
python
|
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
|
Directly call a salt command in the modules, does not require a running
salt minion to run.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L429-L439
|
[
"def _install_signal_handlers(client):\n # Install the SIGINT/SIGTERM handlers if not done so far\n if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n\n if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_run
|
python
|
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
|
Execute a salt convenience routine.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L442-L451
|
[
"def _install_signal_handlers(client):\n # Install the SIGINT/SIGTERM handlers if not done so far\n if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n\n if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_ssh
|
python
|
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
|
Execute the salt-ssh system
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L454-L474
|
[
"def _install_signal_handlers(client):\n # Install the SIGINT/SIGTERM handlers if not done so far\n if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n\n if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n",
"def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):\n '''\n if hardfailing:\n If we got the original stacktrace, log it\n If all cases, raise the original exception\n but this is logically part the initial\n stack.\n else just let salt exit gracefully\n\n '''\n if hardfail:\n if trace:\n log.error(trace)\n raise original_exc\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_cloud
|
python
|
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
|
The main function for salt-cloud
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L477-L499
|
[
"def _install_signal_handlers(client):\n # Install the SIGINT/SIGTERM handlers if not done so far\n if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n\n if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_api
|
python
|
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
|
The main function for salt-api
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L502-L511
|
[
"def notify_systemd():\n '''\n Notify systemd that this process has started\n '''\n try:\n import systemd.daemon\n except ImportError:\n if salt.utils.path.which('systemd-notify') \\\n and systemd_notify_call('--booted'):\n # Notify systemd synchronously\n notify_socket = os.getenv('NOTIFY_SOCKET')\n if notify_socket:\n # Handle abstract namespace socket\n if notify_socket.startswith('@'):\n notify_socket = '\\0{0}'.format(notify_socket[1:])\n try:\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)\n sock.connect(notify_socket)\n sock.sendall('READY=1'.encode())\n sock.close()\n except socket.error:\n return systemd_notify_call('--ready')\n return True\n return False\n\n if systemd.daemon.booted():\n try:\n return systemd.daemon.notify('READY=1')\n except SystemError:\n # Daemon was not started by systemd\n pass\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_main
|
python
|
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
|
Publish commands to the salt system from the command line on the
master.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L514-L524
|
[
"def _install_signal_handlers(client):\n # Install the SIGINT/SIGTERM handlers if not done so far\n if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n\n if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_spm
|
python
|
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
|
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L527-L535
| null |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_extend
|
python
|
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
|
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L538-L549
|
[
"def run(extension=None, name=None, description=None, salt_dir=None, merge=False, temp_dir=None):\n '''\n A template factory for extending the salt ecosystem\n\n :param extension: The extension type, e.g. 'module', 'state', if omitted, user will be prompted\n :type extension: ``str``\n\n :param name: Python-friendly name for the module, if omitted, user will be prompted\n :type name: ``str``\n\n :param description: A description of the extension, if omitted, user will be prompted\n :type description: ``str``\n\n :param salt_dir: The targeted Salt source directory\n :type salt_dir: ``str``\n\n :param merge: Merge with salt directory, `False` to keep separate, `True` to merge trees.\n :type merge: ``bool``\n\n :param temp_dir: The directory for generated code, if omitted, system temp will be used\n :type temp_dir: ``str``\n '''\n if not HAS_CLICK:\n print(\"click is not installed, please install using pip\")\n sys.exit(1)\n\n if salt_dir is None:\n salt_dir = '.'\n\n MODULE_OPTIONS = _fetch_templates(os.path.join(salt_dir, 'templates'))\n\n if extension is None:\n print('Choose which type of extension you are developing for SaltStack')\n extension_type = 'Extension type'\n chosen_extension = _prompt_choice(extension_type, MODULE_OPTIONS)\n else:\n if extension not in list(zip(*MODULE_OPTIONS))[0]:\n print(\"Module extension option not valid\")\n sys.exit(1)\n\n chosen_extension = [m for m in MODULE_OPTIONS if m[0] == extension][0]\n\n extension_type = chosen_extension[0]\n extension_context = chosen_extension[2]\n\n if name is None:\n print('Enter the short name for the module (e.g. mymodule)')\n name = _prompt_user_variable('Module name', '')\n\n if description is None:\n description = _prompt_user_variable('Short description of the module', '')\n\n template_dir = 'templates/{0}'.format(extension_type)\n module_name = name\n\n param_dict = {\n \"version\": salt.version.SaltStackVersion.next_release().name,\n \"module_name\": module_name,\n \"short_description\": description,\n \"release_date\": date.today().strftime('%Y-%m-%d'),\n \"year\": date.today().strftime('%Y'),\n }\n\n # get additional questions from template\n additional_context = {}\n for key, val in extension_context.get('questions', {}).items():\n # allow templates to be used in default values.\n default = Template(val.get('default', '')).render(param_dict)\n\n prompt_var = _prompt_user_variable(val['question'], default)\n additional_context[key] = prompt_var\n\n context = param_dict.copy()\n context.update(extension_context)\n context.update(additional_context)\n\n if temp_dir is None:\n temp_dir = tempfile.mkdtemp()\n\n apply_template(\n template_dir,\n temp_dir,\n context)\n\n if not merge:\n path = temp_dir\n else:\n _mergetree(temp_dir, salt_dir)\n path = salt_dir\n\n log.info('New module stored in %s', path)\n return path\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
saltstack/salt
|
salt/scripts.py
|
salt_support
|
python
|
def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
client.run()
|
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L552-L563
|
[
"def _install_signal_handlers(client):\n # Install the SIGINT/SIGTERM handlers if not done so far\n if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n\n if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:\n # No custom signal handling was added, install our own\n signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))\n"
] |
# -*- coding: utf-8 -*-
'''
This module contains the function calls to execute command line scripts
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import time
import signal
import logging
import functools
import threading
import traceback
import signal
import functools
from random import randint
# Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError
import salt.defaults.exitcodes # pylint: disable=unused-import
import salt.ext.six as six
log = logging.getLogger(__name__)
def _handle_interrupt(exc, original_exc, hardfail=False, trace=''):
'''
if hardfailing:
If we got the original stacktrace, log it
If all cases, raise the original exception
but this is logically part the initial
stack.
else just let salt exit gracefully
'''
if hardfail:
if trace:
log.error(trace)
raise original_exc
else:
raise exc
def _handle_signals(client, signum, sigframe):
try:
# This raises AttributeError on Python 3.4 and 3.5 if there is no current exception.
# Ref: https://bugs.python.org/issue23003
trace = traceback.format_exc()
except AttributeError:
trace = ''
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
if signum == signal.SIGINT:
exit_msg = '\nExiting gracefully on Ctrl-c'
try:
jid = client.local_client.pub_data['jid']
target = client.local_client.target_data
exit_msg += (
'\n'
'This job\'s jid is: {0}\n'
'The minions may not have all finished running and any remaining '
'minions will return upon completion.\n\n'
'To look up the return data for this job later, run the '
'following command:\n'
'salt-run jobs.lookup_jid {0}'.format(jid)
)
if target:
exit_msg += (
'\n\n'
'To set up the state run to safely exit, run the following command:\n'
'salt {0} state.soft_kill {1}'.format(target, jid)
)
except (AttributeError, KeyError):
pass
else:
exit_msg = None
_handle_interrupt(
SystemExit(exit_msg),
Exception('\nExiting with hard crash on Ctrl-c'),
hardcrash, trace=trace)
def _install_signal_handlers(client):
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, functools.partial(_handle_signals, client))
def salt_master():
'''
Start the salt master.
'''
import salt.cli.daemons
# REMOVEME after Python 2.7 support is dropped (also the six import)
if six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
master = salt.cli.daemons.Master()
master.start()
def minion_process():
'''
Start a minion process
'''
import salt.utils.platform
import salt.utils.process
import salt.cli.daemons
# salt_minion spawns this function in a new process
salt.utils.process.appendproctitle('KeepAlive')
def handle_hup(manager, sig, frame):
manager.minion.reload()
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: small race issue where the parent PID could be replace
with another process with same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
if os.getuid() == 0 and not salt.utils.platform.is_windows():
os.kill(parent_pid, 0)
except OSError as exc:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
log.error('Minion process encountered exception: %s', exc)
os._exit(salt.defaults.exitcodes.EX_GENERIC)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
minion = salt.cli.daemons.Minion()
signal.signal(signal.SIGHUP,
functools.partial(handle_hup,
minion))
minion.start()
except (SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
lock.acquire(blocking=True)
log.warning('Fatal functionality error caught by minion handler:\n', exc_info=True)
log.warning('** Restarting minion **')
delay = 60
if minion is not None and hasattr(minion, 'config'):
delay = minion.config.get('random_reauth_delay', 60)
delay = randint(1, delay)
log.info('waiting random_reauth_delay %ss', delay)
time.sleep(delay)
sys.exit(salt.defaults.exitcodes.SALT_KEEPALIVE)
finally:
lock.acquire(blocking=True)
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
minion = salt.cli.daemons.Minion()
minion.start()
return
# REMOVEME after Python 2.7 support is dropped (also the six import)
elif six.PY2:
from salt.utils.versions import warn_until
# Message borrowed from pip's deprecation warning
warn_until('Sodium',
'Python 2.7 will reach the end of its life on January 1st,'
' 2020. Please upgrade your Python as Python 2.7 won\'t be'
' maintained after that date. Salt will drop support for'
' Python 2.7 in the Sodium release or later.')
# END REMOVEME
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
minion = salt.cli.daemons.Minion()
minion.start()
return
def escalate_signal_to_process(pid, signum, sigframe): # pylint: disable=unused-argument
'''
Escalate the signal received to the multiprocessing process that
is actually running the minion
'''
# escalate signal
os.kill(pid, signum)
# keep one minion subprocess running
prev_sigint_handler = signal.getsignal(signal.SIGINT)
prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
while True:
try:
process = multiprocessing.Process(target=minion_process)
process.start()
signal.signal(signal.SIGTERM,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGINT,
functools.partial(escalate_signal_to_process,
process.pid))
signal.signal(signal.SIGHUP,
functools.partial(escalate_signal_to_process,
process.pid))
except Exception: # pylint: disable=broad-except
# if multiprocessing does not work
minion = salt.cli.daemons.Minion()
minion.start()
break
process.join()
# Process exited or was terminated. Since we're going to try to restart
# it, we MUST, reset signal handling to the previous handlers
signal.signal(signal.SIGINT, prev_sigint_handler)
signal.signal(signal.SIGTERM, prev_sigterm_handler)
if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
sys.exit(process.exitcode)
# ontop of the random_reauth_delay already preformed
# delay extra to reduce flooding and free resources
# NOTE: values are static but should be fine.
time.sleep(2 + randint(1, 10))
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def proxy_minion_process(queue):
'''
Start a proxy minion process
'''
import salt.cli.daemons
import salt.utils.platform
# salt_minion spawns this function in a new process
lock = threading.RLock()
def suicide_when_without_parent(parent_pid):
'''
Have the minion suicide if the parent process is gone
NOTE: there is a small race issue where the parent PID could be replace
with another process with the same PID!
'''
while lock.acquire(blocking=False):
lock.release()
time.sleep(5)
try:
# check pid alive (Unix only trick!)
os.kill(parent_pid, 0)
except OSError:
# forcibly exit, regular sys.exit raises an exception-- which
# isn't sufficient in a thread
os._exit(999)
try:
if not salt.utils.platform.is_windows():
thread = threading.Thread(target=suicide_when_without_parent, args=(os.getppid(),))
thread.start()
restart = False
proxyminion = None
status = salt.defaults.exitcodes.EX_OK
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error('Proxy Minion failed to start: ', exc_info=True)
restart = True
# status is superfluous since the process will be restarted
status = salt.defaults.exitcodes.SALT_KEEPALIVE
except SystemExit as exc:
restart = False
status = exc.code
finally:
lock.acquire(blocking=True)
if restart is True:
log.warning('** Restarting proxy minion **')
delay = 60
if proxyminion is not None:
if hasattr(proxyminion, 'config'):
delay = proxyminion.config.get('random_reauth_delay', 60)
random_delay = randint(1, delay)
log.info('Sleeping random_reauth_delay of %s seconds', random_delay)
# preform delay after minion resources have been cleaned
queue.put(random_delay)
else:
queue.put(0)
sys.exit(status)
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
if '--disable-keepalive' in sys.argv:
sys.argv.remove('--disable-keepalive')
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
# keep one minion subprocess running
while True:
try:
queue = multiprocessing.Queue()
except Exception:
# This breaks in containers
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
return
process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
process.start()
try:
process.join()
try:
restart_delay = queue.get(block=False)
except Exception:
if process.exitcode == 0:
# Minion process ended naturally, Ctrl+C or --version
break
restart_delay = 60
if restart_delay == 0:
# Minion process ended naturally, Ctrl+C, --version, etc.
sys.exit(process.exitcode)
# delay restart to reduce flooding and allow network resources to close
time.sleep(restart_delay)
except KeyboardInterrupt:
break
# need to reset logging because new minion objects
# cause extra log handlers to accumulate
rlogger = logging.getLogger()
for handler in rlogger.handlers:
rlogger.removeHandler(handler)
logging.basicConfig()
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15)
def salt_key():
'''
Manage the authentication keys with salt-key.
'''
import salt.cli.key
try:
client = salt.cli.key.SaltKey()
_install_signal_handlers(client)
client.run()
except Exception as err:
sys.stderr.write("Error: {0}\n".format(err))
def salt_cp():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.cp
client = salt.cli.cp.SaltCPCli()
_install_signal_handlers(client)
client.run()
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run()
def salt_run():
'''
Execute a salt convenience routine.
'''
import salt.cli.run
if '' in sys.path:
sys.path.remove('')
client = salt.cli.run.SaltRun()
_install_signal_handlers(client)
client.run()
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_exc()
try:
hardcrash = client.options.hard_crash
except (AttributeError, KeyError):
hardcrash = False
_handle_interrupt(
SystemExit(err),
err,
hardcrash, trace=trace)
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import salt.cloud.cli
except ImportError as e:
# No salt cloud on Windows
log.error('Error importing salt cloud: %s', e)
print('salt-cloud is not available in this system')
sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
if '' in sys.path:
sys.path.remove('')
client = salt.cloud.cli.SaltCloud()
_install_signal_handlers(client)
client.run()
def salt_api():
'''
The main function for salt-api
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.api
sapi = salt.cli.api.SaltAPI() # pylint: disable=E1120
sapi.start()
def salt_main():
'''
Publish commands to the salt system from the command line on the
master.
'''
import salt.cli.salt
if '' in sys.path:
sys.path.remove('')
client = salt.cli.salt.SaltCMD()
_install_signal_handlers(client)
client.run()
def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run()
def salt_extend(extension, name, description, salt_dir, merge):
'''
Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0
'''
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge)
|
saltstack/salt
|
salt/pillar/puppet.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
command):
'''
Execute an unmodified puppet_node_classifier and read the output as YAML
'''
try:
data = salt.utils.yaml.safe_load(__salt__['cmd.run']('{0} {1}'.format(command, minion_id)))
return data['parameters']
except Exception:
log.critical('YAML data from %s failed to parse', command)
return {}
|
Execute an unmodified puppet_node_classifier and read the output as YAML
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/puppet.py#L20-L31
|
[
"def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n"
] |
# -*- coding: utf-8 -*-
'''
Execute an unmodified puppet_node_classifier and read the output as YAML. The YAML data is then directly overlaid onto the minion's Pillar data.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Don't "fix" the above docstring to put it on two lines, as the sphinx
# autosummary pulls only the first line for its description.
# Import Python libs
import logging
# Import Salt libs
import salt.utils.yaml
# Set up logging
log = logging.getLogger(__name__)
|
saltstack/salt
|
salt/modules/win_wusa.py
|
_pshell_json
|
python
|
def _pshell_json(cmd, cwd=None):
'''
Execute the desired powershell command and ensure that it returns data
in JSON format and load that into python
'''
if 'convertto-json' not in cmd.lower():
cmd = '{0} | ConvertTo-Json'.format(cmd)
log.debug('PowerShell: %s', cmd)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd)
if 'pid' in ret:
del ret['pid']
if ret.get('stderr', ''):
error = ret['stderr'].splitlines()[0]
raise CommandExecutionError(error, info=ret)
if 'retcode' not in ret or ret['retcode'] != 0:
# run_all logs an error to log.error, fail hard back to the user
raise CommandExecutionError(
'Issue executing PowerShell {0}'.format(cmd), info=ret)
# Sometimes Powershell returns an empty string, which isn't valid JSON
if ret['stdout'] == '':
ret['stdout'] = '{}'
try:
ret = salt.utils.json.loads(ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError(
'No JSON results from PowerShell', info=ret)
return ret
|
Execute the desired powershell command and ensure that it returns data
in JSON format and load that into python
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wusa.py#L41-L73
| null |
# -*- coding: utf-8 -*-
'''
Microsoft Update files management via wusa.exe
:maintainer: Thomas Lemarchand
:platform: Windows
:depends: PowerShell
.. versionadded:: 2018.3.4
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
import os
# Import salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'wusa'
def __virtual__():
'''
Load only on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'Only available on Windows systems'
powershell_info = __salt__['cmd.shell_info'](shell='powershell', list_modules=False)
if not powershell_info['installed']:
return False, 'PowerShell not available'
return __virtualname__
def is_installed(name):
'''
Check if a specific KB is installed.
Args:
name (str):
The name of the KB to check
Returns:
bool: ``True`` if installed, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' wusa.is_installed KB123456
'''
return __salt__['cmd.retcode'](cmd='Get-HotFix -Id {0}'.format(name),
shell='powershell',
ignore_retcode=True) == 0
def install(path, restart=False):
'''
Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raise:
CommandExecutionError: If the package is already installed or an error
is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.install C:/temp/KB123456.msu
'''
# Build the command
cmd = ['wusa.exe', path, '/quiet']
if restart:
cmd.append('/forcerestart')
else:
cmd.append('/norestart')
# Run the command
ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)
# Check the ret_code
file_name = os.path.basename(path)
errors = {2359302: '{0} is already installed'.format(file_name),
87: 'Unknown error'}
if ret_code in errors:
raise CommandExecutionError(errors[ret_code])
elif ret_code:
raise CommandExecutionError('Unknown error: {0}'.format(ret_code))
return True
def uninstall(path, restart=False):
'''
Uninstall a specific KB.
Args:
path (str):
The full path to the msu file to uninstall. This can also be just
the name of the KB to uninstall
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If an error is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.uninstall KB123456
# or
salt '*' wusa.uninstall C:/temp/KB123456.msu
'''
# Build the command
cmd = ['wusa.exe', '/uninstall', '/quiet']
kb = os.path.splitext(os.path.basename(path))[0]
if os.path.exists(path):
cmd.append(path)
else:
cmd.append(
'/kb:{0}'.format(kb[2:] if kb.lower().startswith('kb') else kb))
if restart:
cmd.append('/forcerestart')
else:
cmd.append('/norestart')
# Run the command
ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)
# Check the ret_code
# If you pass /quiet and specify /kb, you'll always get retcode 87 if there
# is an error. Use the actual file to get a more descriptive error
errors = {-2145116156: '{0} does not support uninstall'.format(kb),
2359303: '{0} not installed'.format(kb),
87: 'Unknown error. Try specifying an .msu file'}
if ret_code in errors:
raise CommandExecutionError(errors[ret_code])
elif ret_code:
raise CommandExecutionError('Unknown error: {0}'.format(ret_code))
return True
def list():
'''
Get a list of updates installed on the machine
Returns:
list: A list of installed updates
CLI Example:
.. code-block:: bash
salt '*' wusa.list
'''
kbs = []
ret = _pshell_json('Get-HotFix | Select HotFixID')
for item in ret:
kbs.append(item['HotFixID'])
return kbs
|
saltstack/salt
|
salt/modules/win_wusa.py
|
install
|
python
|
def install(path, restart=False):
'''
Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raise:
CommandExecutionError: If the package is already installed or an error
is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.install C:/temp/KB123456.msu
'''
# Build the command
cmd = ['wusa.exe', path, '/quiet']
if restart:
cmd.append('/forcerestart')
else:
cmd.append('/norestart')
# Run the command
ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)
# Check the ret_code
file_name = os.path.basename(path)
errors = {2359302: '{0} is already installed'.format(file_name),
87: 'Unknown error'}
if ret_code in errors:
raise CommandExecutionError(errors[ret_code])
elif ret_code:
raise CommandExecutionError('Unknown error: {0}'.format(ret_code))
return True
|
Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raise:
CommandExecutionError: If the package is already installed or an error
is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.install C:/temp/KB123456.msu
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wusa.py#L99-L145
| null |
# -*- coding: utf-8 -*-
'''
Microsoft Update files management via wusa.exe
:maintainer: Thomas Lemarchand
:platform: Windows
:depends: PowerShell
.. versionadded:: 2018.3.4
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
import os
# Import salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'wusa'
def __virtual__():
'''
Load only on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'Only available on Windows systems'
powershell_info = __salt__['cmd.shell_info'](shell='powershell', list_modules=False)
if not powershell_info['installed']:
return False, 'PowerShell not available'
return __virtualname__
def _pshell_json(cmd, cwd=None):
'''
Execute the desired powershell command and ensure that it returns data
in JSON format and load that into python
'''
if 'convertto-json' not in cmd.lower():
cmd = '{0} | ConvertTo-Json'.format(cmd)
log.debug('PowerShell: %s', cmd)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd)
if 'pid' in ret:
del ret['pid']
if ret.get('stderr', ''):
error = ret['stderr'].splitlines()[0]
raise CommandExecutionError(error, info=ret)
if 'retcode' not in ret or ret['retcode'] != 0:
# run_all logs an error to log.error, fail hard back to the user
raise CommandExecutionError(
'Issue executing PowerShell {0}'.format(cmd), info=ret)
# Sometimes Powershell returns an empty string, which isn't valid JSON
if ret['stdout'] == '':
ret['stdout'] = '{}'
try:
ret = salt.utils.json.loads(ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError(
'No JSON results from PowerShell', info=ret)
return ret
def is_installed(name):
'''
Check if a specific KB is installed.
Args:
name (str):
The name of the KB to check
Returns:
bool: ``True`` if installed, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' wusa.is_installed KB123456
'''
return __salt__['cmd.retcode'](cmd='Get-HotFix -Id {0}'.format(name),
shell='powershell',
ignore_retcode=True) == 0
def uninstall(path, restart=False):
'''
Uninstall a specific KB.
Args:
path (str):
The full path to the msu file to uninstall. This can also be just
the name of the KB to uninstall
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If an error is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.uninstall KB123456
# or
salt '*' wusa.uninstall C:/temp/KB123456.msu
'''
# Build the command
cmd = ['wusa.exe', '/uninstall', '/quiet']
kb = os.path.splitext(os.path.basename(path))[0]
if os.path.exists(path):
cmd.append(path)
else:
cmd.append(
'/kb:{0}'.format(kb[2:] if kb.lower().startswith('kb') else kb))
if restart:
cmd.append('/forcerestart')
else:
cmd.append('/norestart')
# Run the command
ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)
# Check the ret_code
# If you pass /quiet and specify /kb, you'll always get retcode 87 if there
# is an error. Use the actual file to get a more descriptive error
errors = {-2145116156: '{0} does not support uninstall'.format(kb),
2359303: '{0} not installed'.format(kb),
87: 'Unknown error. Try specifying an .msu file'}
if ret_code in errors:
raise CommandExecutionError(errors[ret_code])
elif ret_code:
raise CommandExecutionError('Unknown error: {0}'.format(ret_code))
return True
def list():
'''
Get a list of updates installed on the machine
Returns:
list: A list of installed updates
CLI Example:
.. code-block:: bash
salt '*' wusa.list
'''
kbs = []
ret = _pshell_json('Get-HotFix | Select HotFixID')
for item in ret:
kbs.append(item['HotFixID'])
return kbs
|
saltstack/salt
|
salt/modules/win_wusa.py
|
uninstall
|
python
|
def uninstall(path, restart=False):
'''
Uninstall a specific KB.
Args:
path (str):
The full path to the msu file to uninstall. This can also be just
the name of the KB to uninstall
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If an error is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.uninstall KB123456
# or
salt '*' wusa.uninstall C:/temp/KB123456.msu
'''
# Build the command
cmd = ['wusa.exe', '/uninstall', '/quiet']
kb = os.path.splitext(os.path.basename(path))[0]
if os.path.exists(path):
cmd.append(path)
else:
cmd.append(
'/kb:{0}'.format(kb[2:] if kb.lower().startswith('kb') else kb))
if restart:
cmd.append('/forcerestart')
else:
cmd.append('/norestart')
# Run the command
ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)
# Check the ret_code
# If you pass /quiet and specify /kb, you'll always get retcode 87 if there
# is an error. Use the actual file to get a more descriptive error
errors = {-2145116156: '{0} does not support uninstall'.format(kb),
2359303: '{0} not installed'.format(kb),
87: 'Unknown error. Try specifying an .msu file'}
if ret_code in errors:
raise CommandExecutionError(errors[ret_code])
elif ret_code:
raise CommandExecutionError('Unknown error: {0}'.format(ret_code))
return True
|
Uninstall a specific KB.
Args:
path (str):
The full path to the msu file to uninstall. This can also be just
the name of the KB to uninstall
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If an error is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.uninstall KB123456
# or
salt '*' wusa.uninstall C:/temp/KB123456.msu
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wusa.py#L148-L206
| null |
# -*- coding: utf-8 -*-
'''
Microsoft Update files management via wusa.exe
:maintainer: Thomas Lemarchand
:platform: Windows
:depends: PowerShell
.. versionadded:: 2018.3.4
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
import os
# Import salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'wusa'
def __virtual__():
'''
Load only on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'Only available on Windows systems'
powershell_info = __salt__['cmd.shell_info'](shell='powershell', list_modules=False)
if not powershell_info['installed']:
return False, 'PowerShell not available'
return __virtualname__
def _pshell_json(cmd, cwd=None):
'''
Execute the desired powershell command and ensure that it returns data
in JSON format and load that into python
'''
if 'convertto-json' not in cmd.lower():
cmd = '{0} | ConvertTo-Json'.format(cmd)
log.debug('PowerShell: %s', cmd)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd)
if 'pid' in ret:
del ret['pid']
if ret.get('stderr', ''):
error = ret['stderr'].splitlines()[0]
raise CommandExecutionError(error, info=ret)
if 'retcode' not in ret or ret['retcode'] != 0:
# run_all logs an error to log.error, fail hard back to the user
raise CommandExecutionError(
'Issue executing PowerShell {0}'.format(cmd), info=ret)
# Sometimes Powershell returns an empty string, which isn't valid JSON
if ret['stdout'] == '':
ret['stdout'] = '{}'
try:
ret = salt.utils.json.loads(ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError(
'No JSON results from PowerShell', info=ret)
return ret
def is_installed(name):
'''
Check if a specific KB is installed.
Args:
name (str):
The name of the KB to check
Returns:
bool: ``True`` if installed, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' wusa.is_installed KB123456
'''
return __salt__['cmd.retcode'](cmd='Get-HotFix -Id {0}'.format(name),
shell='powershell',
ignore_retcode=True) == 0
def install(path, restart=False):
'''
Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raise:
CommandExecutionError: If the package is already installed or an error
is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.install C:/temp/KB123456.msu
'''
# Build the command
cmd = ['wusa.exe', path, '/quiet']
if restart:
cmd.append('/forcerestart')
else:
cmd.append('/norestart')
# Run the command
ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)
# Check the ret_code
file_name = os.path.basename(path)
errors = {2359302: '{0} is already installed'.format(file_name),
87: 'Unknown error'}
if ret_code in errors:
raise CommandExecutionError(errors[ret_code])
elif ret_code:
raise CommandExecutionError('Unknown error: {0}'.format(ret_code))
return True
def list():
'''
Get a list of updates installed on the machine
Returns:
list: A list of installed updates
CLI Example:
.. code-block:: bash
salt '*' wusa.list
'''
kbs = []
ret = _pshell_json('Get-HotFix | Select HotFixID')
for item in ret:
kbs.append(item['HotFixID'])
return kbs
|
saltstack/salt
|
salt/modules/win_wusa.py
|
list
|
python
|
def list():
'''
Get a list of updates installed on the machine
Returns:
list: A list of installed updates
CLI Example:
.. code-block:: bash
salt '*' wusa.list
'''
kbs = []
ret = _pshell_json('Get-HotFix | Select HotFixID')
for item in ret:
kbs.append(item['HotFixID'])
return kbs
|
Get a list of updates installed on the machine
Returns:
list: A list of installed updates
CLI Example:
.. code-block:: bash
salt '*' wusa.list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wusa.py#L209-L226
|
[
"def _pshell_json(cmd, cwd=None):\n '''\n Execute the desired powershell command and ensure that it returns data\n in JSON format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json'.format(cmd)\n log.debug('PowerShell: %s', cmd)\n ret = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd)\n\n if 'pid' in ret:\n del ret['pid']\n\n if ret.get('stderr', ''):\n error = ret['stderr'].splitlines()[0]\n raise CommandExecutionError(error, info=ret)\n\n if 'retcode' not in ret or ret['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError(\n 'Issue executing PowerShell {0}'.format(cmd), info=ret)\n\n # Sometimes Powershell returns an empty string, which isn't valid JSON\n if ret['stdout'] == '':\n ret['stdout'] = '{}'\n\n try:\n ret = salt.utils.json.loads(ret['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError(\n 'No JSON results from PowerShell', info=ret)\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Microsoft Update files management via wusa.exe
:maintainer: Thomas Lemarchand
:platform: Windows
:depends: PowerShell
.. versionadded:: 2018.3.4
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
import os
# Import salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'wusa'
def __virtual__():
'''
Load only on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'Only available on Windows systems'
powershell_info = __salt__['cmd.shell_info'](shell='powershell', list_modules=False)
if not powershell_info['installed']:
return False, 'PowerShell not available'
return __virtualname__
def _pshell_json(cmd, cwd=None):
'''
Execute the desired powershell command and ensure that it returns data
in JSON format and load that into python
'''
if 'convertto-json' not in cmd.lower():
cmd = '{0} | ConvertTo-Json'.format(cmd)
log.debug('PowerShell: %s', cmd)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd)
if 'pid' in ret:
del ret['pid']
if ret.get('stderr', ''):
error = ret['stderr'].splitlines()[0]
raise CommandExecutionError(error, info=ret)
if 'retcode' not in ret or ret['retcode'] != 0:
# run_all logs an error to log.error, fail hard back to the user
raise CommandExecutionError(
'Issue executing PowerShell {0}'.format(cmd), info=ret)
# Sometimes Powershell returns an empty string, which isn't valid JSON
if ret['stdout'] == '':
ret['stdout'] = '{}'
try:
ret = salt.utils.json.loads(ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError(
'No JSON results from PowerShell', info=ret)
return ret
def is_installed(name):
'''
Check if a specific KB is installed.
Args:
name (str):
The name of the KB to check
Returns:
bool: ``True`` if installed, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' wusa.is_installed KB123456
'''
return __salt__['cmd.retcode'](cmd='Get-HotFix -Id {0}'.format(name),
shell='powershell',
ignore_retcode=True) == 0
def install(path, restart=False):
'''
Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raise:
CommandExecutionError: If the package is already installed or an error
is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.install C:/temp/KB123456.msu
'''
# Build the command
cmd = ['wusa.exe', path, '/quiet']
if restart:
cmd.append('/forcerestart')
else:
cmd.append('/norestart')
# Run the command
ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)
# Check the ret_code
file_name = os.path.basename(path)
errors = {2359302: '{0} is already installed'.format(file_name),
87: 'Unknown error'}
if ret_code in errors:
raise CommandExecutionError(errors[ret_code])
elif ret_code:
raise CommandExecutionError('Unknown error: {0}'.format(ret_code))
return True
def uninstall(path, restart=False):
'''
Uninstall a specific KB.
Args:
path (str):
The full path to the msu file to uninstall. This can also be just
the name of the KB to uninstall
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add the ``/norestart`` switch instead. Default is ``False``
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If an error is encountered
CLI Example:
.. code-block:: bash
salt '*' wusa.uninstall KB123456
# or
salt '*' wusa.uninstall C:/temp/KB123456.msu
'''
# Build the command
cmd = ['wusa.exe', '/uninstall', '/quiet']
kb = os.path.splitext(os.path.basename(path))[0]
if os.path.exists(path):
cmd.append(path)
else:
cmd.append(
'/kb:{0}'.format(kb[2:] if kb.lower().startswith('kb') else kb))
if restart:
cmd.append('/forcerestart')
else:
cmd.append('/norestart')
# Run the command
ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)
# Check the ret_code
# If you pass /quiet and specify /kb, you'll always get retcode 87 if there
# is an error. Use the actual file to get a more descriptive error
errors = {-2145116156: '{0} does not support uninstall'.format(kb),
2359303: '{0} not installed'.format(kb),
87: 'Unknown error. Try specifying an .msu file'}
if ret_code in errors:
raise CommandExecutionError(errors[ret_code])
elif ret_code:
raise CommandExecutionError('Unknown error: {0}'.format(ret_code))
return True
|
saltstack/salt
|
salt/states/net_napalm_yang.py
|
managed
|
python
|
def managed(name,
data,
**kwargs):
'''
Manage the device configuration given the input data structured
according to the YANG models.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
compliance_report: ``False``
Return the compliance report in the comment.
.. versionadded:: 2017.7.3
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.managed:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example"
'''
models = kwargs.get('models', None)
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = kwargs.get('test', False) or __opts__.get('test', False)
debug = kwargs.get('debug', False) or __opts__.get('debug', False)
commit = kwargs.get('commit', True) or __opts__.get('commit', True)
replace = kwargs.get('replace', False) or __opts__.get('replace', False)
return_compliance_report = kwargs.get('compliance_report', False) or __opts__.get('compliance_report', False)
profiles = kwargs.get('profiles', [])
temp_file = __salt__['temp.file']()
log.debug('Creating temp file: %s', temp_file)
if 'to_dict' not in data:
data = {'to_dict': data}
data = [data]
with salt.utils.files.fopen(temp_file, 'w') as file_handle:
salt.utils.yaml.safe_dump(
salt.utils.json.loads(salt.utils.json.dumps(data)),
file_handle,
encoding='utf-8'
)
device_config = __salt__['napalm_yang.parse'](*models,
config=True,
profiles=profiles)
log.debug('Parsed the config from the device:')
log.debug(device_config)
compliance_report = __salt__['napalm_yang.compliance_report'](device_config,
*models,
filepath=temp_file)
log.debug('Compliance report:')
log.debug(compliance_report)
complies = compliance_report.get('complies', False)
if complies:
ret.update({
'result': True,
'comment': 'Already configured as required.'
})
log.debug('All good here.')
return ret
log.debug('Does not comply, trying to generate and load config')
data = data[0]['to_dict']
if '_kwargs' in data:
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data,
*models,
profiles=profiles,
test=test,
debug=debug,
commit=commit,
replace=replace)
log.debug('Loaded config result:')
log.debug(loaded_changes)
__salt__['file.remove'](temp_file)
loaded_changes['compliance_report'] = compliance_report
return salt.utils.napalm.loaded_ret(ret,
loaded_changes,
test,
debug,
opts=__opts__,
compliance_report=return_compliance_report)
|
Manage the device configuration given the input data structured
according to the YANG models.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
compliance_report: ``False``
Return the compliance report in the comment.
.. versionadded:: 2017.7.3
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.managed:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/net_napalm_yang.py#L78-L202
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def safe_dump(data, stream=None, **kwargs):\n '''\n Use a custom dumper to ensure that defaultdict and OrderedDict are\n represented properly. Ensure that unicode strings are encoded unless\n explicitly told not to.\n '''\n if 'allow_unicode' not in kwargs:\n kwargs['allow_unicode'] = True\n return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)\n",
"def default_ret(name):\n '''\n Return the default dict of the state output.\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'result': False,\n 'comment': ''\n }\n return ret\n",
"def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None):\n '''\n Return the final state output.\n ret\n The initial state output structure.\n loaded\n The loaded dictionary.\n '''\n # Always get the comment\n changes = {}\n ret['comment'] = loaded['comment']\n if 'diff' in loaded:\n changes['diff'] = loaded['diff']\n if 'commit_id' in loaded:\n changes['commit_id'] = loaded['commit_id']\n if 'compliance_report' in loaded:\n if compliance_report:\n changes['compliance_report'] = loaded['compliance_report']\n if debug and 'loaded_config' in loaded:\n changes['loaded_config'] = loaded['loaded_config']\n if changes.get('diff'):\n ret['comment'] = '{comment_base}\\n\\nConfiguration diff:\\n\\n{diff}'.format(comment_base=ret['comment'],\n diff=changes['diff'])\n if changes.get('loaded_config'):\n ret['comment'] = '{comment_base}\\n\\nLoaded config:\\n\\n{loaded_cfg}'.format(\n comment_base=ret['comment'],\n loaded_cfg=changes['loaded_config'])\n if changes.get('compliance_report'):\n ret['comment'] = '{comment_base}\\n\\nCompliance report:\\n\\n{compliance}'.format(\n comment_base=ret['comment'],\n compliance=salt.output.string_format(changes['compliance_report'], 'nested', opts=opts))\n if not loaded.get('result', False):\n # Failure of some sort\n return ret\n if not loaded.get('already_configured', True):\n # We're making changes\n if test:\n ret['result'] = None\n return ret\n # Not test, changes were applied\n ret.update({\n 'result': True,\n 'changes': changes,\n 'comment': \"Configuration changed!\\n{}\".format(loaded['comment'])\n })\n return ret\n # No changes\n ret.update({\n 'result': True,\n 'changes': {}\n })\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM YANG state
=================
Manage the configuration of network devices according to
the YANG models (OpenConfig/IETF).
.. versionadded:: 2017.7.0
Dependencies
------------
- napalm-yang
- pyangbind > 0.5.11
To be able to load configuration on network devices,
it requires NAPALM_ library to be installed: ``pip install napalm``.
Please check Installation_ for complete details.
.. _NAPALM: https://napalm.readthedocs.io
.. _Installation: https://napalm.readthedocs.io/en/latest/installation.html
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
log = logging.getLogger(__file__)
# Import third party libs
try:
# pylint: disable=unused-import
import napalm_yang
HAS_NAPALM_YANG = True
# pylint: enable=unused-import
except ImportError:
HAS_NAPALM_YANG = False
# Import salt modules
import salt.utils.files
import salt.utils.json
import salt.utils.napalm
import salt.utils.stringutils
import salt.utils.yaml
# ------------------------------------------------------------------------------
# state properties
# ------------------------------------------------------------------------------
__virtualname__ = 'napalm_yang'
# ------------------------------------------------------------------------------
# global variables
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# property functions
# ------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
This module in particular requires also napalm-yang.
'''
if not HAS_NAPALM_YANG:
return (False, 'Unable to load napalm_yang execution module: please install napalm-yang!')
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ------------------------------------------------------------------------------
# helper functions -- will not be exported
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# callable functions
# ------------------------------------------------------------------------------
def configured(name,
data,
**kwargs):
'''
Configure the network device, given the input data structured
according to the YANG models.
.. note::
The main difference between this function and ``managed``
is that the later generates and loads the configuration
only when there are differences between the existing
configuration on the device and the expected
configuration. Depending on the platform and hardware
capabilities, one could be more optimal than the other.
Additionally, the output of the ``managed`` is different,
in such a way that the ``pchange`` field in the output
contains structured data, rather than text.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.configured:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example"
'''
models = kwargs.get('models', None)
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = kwargs.get('test', False) or __opts__.get('test', False)
debug = kwargs.get('debug', False) or __opts__.get('debug', False)
commit = kwargs.get('commit', True) or __opts__.get('commit', True)
replace = kwargs.get('replace', False) or __opts__.get('replace', False)
profiles = kwargs.get('profiles', [])
if '_kwargs' in data:
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data,
*models,
profiles=profiles,
test=test,
debug=debug,
commit=commit,
replace=replace)
return salt.utils.napalm.loaded_ret(ret, loaded_changes, test, debug)
|
saltstack/salt
|
salt/states/net_napalm_yang.py
|
configured
|
python
|
def configured(name,
data,
**kwargs):
'''
Configure the network device, given the input data structured
according to the YANG models.
.. note::
The main difference between this function and ``managed``
is that the later generates and loads the configuration
only when there are differences between the existing
configuration on the device and the expected
configuration. Depending on the platform and hardware
capabilities, one could be more optimal than the other.
Additionally, the output of the ``managed`` is different,
in such a way that the ``pchange`` field in the output
contains structured data, rather than text.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.configured:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example"
'''
models = kwargs.get('models', None)
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = kwargs.get('test', False) or __opts__.get('test', False)
debug = kwargs.get('debug', False) or __opts__.get('debug', False)
commit = kwargs.get('commit', True) or __opts__.get('commit', True)
replace = kwargs.get('replace', False) or __opts__.get('replace', False)
profiles = kwargs.get('profiles', [])
if '_kwargs' in data:
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data,
*models,
profiles=profiles,
test=test,
debug=debug,
commit=commit,
replace=replace)
return salt.utils.napalm.loaded_ret(ret, loaded_changes, test, debug)
|
Configure the network device, given the input data structured
according to the YANG models.
.. note::
The main difference between this function and ``managed``
is that the later generates and loads the configuration
only when there are differences between the existing
configuration on the device and the expected
configuration. Depending on the platform and hardware
capabilities, one could be more optimal than the other.
Additionally, the output of the ``managed`` is different,
in such a way that the ``pchange`` field in the output
contains structured data, rather than text.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.configured:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/net_napalm_yang.py#L205-L294
|
[
"def default_ret(name):\n '''\n Return the default dict of the state output.\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'result': False,\n 'comment': ''\n }\n return ret\n",
"def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None):\n '''\n Return the final state output.\n ret\n The initial state output structure.\n loaded\n The loaded dictionary.\n '''\n # Always get the comment\n changes = {}\n ret['comment'] = loaded['comment']\n if 'diff' in loaded:\n changes['diff'] = loaded['diff']\n if 'commit_id' in loaded:\n changes['commit_id'] = loaded['commit_id']\n if 'compliance_report' in loaded:\n if compliance_report:\n changes['compliance_report'] = loaded['compliance_report']\n if debug and 'loaded_config' in loaded:\n changes['loaded_config'] = loaded['loaded_config']\n if changes.get('diff'):\n ret['comment'] = '{comment_base}\\n\\nConfiguration diff:\\n\\n{diff}'.format(comment_base=ret['comment'],\n diff=changes['diff'])\n if changes.get('loaded_config'):\n ret['comment'] = '{comment_base}\\n\\nLoaded config:\\n\\n{loaded_cfg}'.format(\n comment_base=ret['comment'],\n loaded_cfg=changes['loaded_config'])\n if changes.get('compliance_report'):\n ret['comment'] = '{comment_base}\\n\\nCompliance report:\\n\\n{compliance}'.format(\n comment_base=ret['comment'],\n compliance=salt.output.string_format(changes['compliance_report'], 'nested', opts=opts))\n if not loaded.get('result', False):\n # Failure of some sort\n return ret\n if not loaded.get('already_configured', True):\n # We're making changes\n if test:\n ret['result'] = None\n return ret\n # Not test, changes were applied\n ret.update({\n 'result': True,\n 'changes': changes,\n 'comment': \"Configuration changed!\\n{}\".format(loaded['comment'])\n })\n return ret\n # No changes\n ret.update({\n 'result': True,\n 'changes': {}\n })\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM YANG state
=================
Manage the configuration of network devices according to
the YANG models (OpenConfig/IETF).
.. versionadded:: 2017.7.0
Dependencies
------------
- napalm-yang
- pyangbind > 0.5.11
To be able to load configuration on network devices,
it requires NAPALM_ library to be installed: ``pip install napalm``.
Please check Installation_ for complete details.
.. _NAPALM: https://napalm.readthedocs.io
.. _Installation: https://napalm.readthedocs.io/en/latest/installation.html
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
log = logging.getLogger(__file__)
# Import third party libs
try:
# pylint: disable=unused-import
import napalm_yang
HAS_NAPALM_YANG = True
# pylint: enable=unused-import
except ImportError:
HAS_NAPALM_YANG = False
# Import salt modules
import salt.utils.files
import salt.utils.json
import salt.utils.napalm
import salt.utils.stringutils
import salt.utils.yaml
# ------------------------------------------------------------------------------
# state properties
# ------------------------------------------------------------------------------
__virtualname__ = 'napalm_yang'
# ------------------------------------------------------------------------------
# global variables
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# property functions
# ------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
This module in particular requires also napalm-yang.
'''
if not HAS_NAPALM_YANG:
return (False, 'Unable to load napalm_yang execution module: please install napalm-yang!')
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ------------------------------------------------------------------------------
# helper functions -- will not be exported
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# callable functions
# ------------------------------------------------------------------------------
def managed(name,
data,
**kwargs):
'''
Manage the device configuration given the input data structured
according to the YANG models.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
compliance_report: ``False``
Return the compliance report in the comment.
.. versionadded:: 2017.7.3
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.managed:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example"
'''
models = kwargs.get('models', None)
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = kwargs.get('test', False) or __opts__.get('test', False)
debug = kwargs.get('debug', False) or __opts__.get('debug', False)
commit = kwargs.get('commit', True) or __opts__.get('commit', True)
replace = kwargs.get('replace', False) or __opts__.get('replace', False)
return_compliance_report = kwargs.get('compliance_report', False) or __opts__.get('compliance_report', False)
profiles = kwargs.get('profiles', [])
temp_file = __salt__['temp.file']()
log.debug('Creating temp file: %s', temp_file)
if 'to_dict' not in data:
data = {'to_dict': data}
data = [data]
with salt.utils.files.fopen(temp_file, 'w') as file_handle:
salt.utils.yaml.safe_dump(
salt.utils.json.loads(salt.utils.json.dumps(data)),
file_handle,
encoding='utf-8'
)
device_config = __salt__['napalm_yang.parse'](*models,
config=True,
profiles=profiles)
log.debug('Parsed the config from the device:')
log.debug(device_config)
compliance_report = __salt__['napalm_yang.compliance_report'](device_config,
*models,
filepath=temp_file)
log.debug('Compliance report:')
log.debug(compliance_report)
complies = compliance_report.get('complies', False)
if complies:
ret.update({
'result': True,
'comment': 'Already configured as required.'
})
log.debug('All good here.')
return ret
log.debug('Does not comply, trying to generate and load config')
data = data[0]['to_dict']
if '_kwargs' in data:
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data,
*models,
profiles=profiles,
test=test,
debug=debug,
commit=commit,
replace=replace)
log.debug('Loaded config result:')
log.debug(loaded_changes)
__salt__['file.remove'](temp_file)
loaded_changes['compliance_report'] = compliance_report
return salt.utils.napalm.loaded_ret(ret,
loaded_changes,
test,
debug,
opts=__opts__,
compliance_report=return_compliance_report)
|
saltstack/salt
|
salt/states/dvs.py
|
_get_datacenter_name
|
python
|
def _get_datacenter_name():
'''
Returns the datacenter name configured on the proxy
Supported proxies: esxcluster, esxdatacenter
'''
proxy_type = __salt__['vsphere.get_proxy_type']()
details = None
if proxy_type == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxy_type == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
if not details:
raise salt.exceptions.CommandExecutionError(
'details for proxy type \'{0}\' not loaded'.format(proxy_type))
return details['datacenter']
|
Returns the datacenter name configured on the proxy
Supported proxies: esxcluster, esxdatacenter
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dvs.py#L245-L261
| null |
# -*- coding: utf-8 -*-
'''
Manage VMware distributed virtual switches (DVSs) and their distributed virtual
portgroups (DVportgroups).
:codeauthor: :email:`Alexandru Bleotu <alexandru.bleotu@morganstaley.com>`
Examples
========
Several settings can be changed for DVSs and DVporgroups. Here are two examples
covering all of the settings. Fewer settings can be used
DVS
---
.. code-block:: python
'name': 'dvs1',
'max_mtu': 1000,
'uplink_names': [
'dvUplink1',
'dvUplink2',
'dvUplink3'
],
'capability': {
'portgroup_operation_supported': false,
'operation_supported': true,
'port_operation_supported': false
},
'lacp_api_version': 'multipleLag',
'contact_email': 'foo@email.com',
'product_info': {
'version':
'6.0.0',
'vendor':
'VMware,
Inc.',
'name':
'DVS'
},
'network_resource_management_enabled': true,
'contact_name': 'me@email.com',
'infrastructure_traffic_resource_pools': [
{
'reservation': 0,
'limit': 1000,
'share_level': 'high',
'key': 'management',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'faultTolerance',
'num_shares': 50
},
{
'reservation': 0,
'limit': 32000,
'share_level': 'normal',
'key': 'vmotion',
'num_shares': 50
},
{
'reservation': 10000,
'limit': -1,
'share_level': 'normal',
'key': 'virtualMachine',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'custom',
'key': 'iSCSI',
'num_shares': 75
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'nfs',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'hbr',
'num_shares': 50
},
{
'reservation': 8750,
'limit': 15000,
'share_level': 'high',
'key': 'vsan',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'vdp',
'num_shares': 50
}
],
'link_discovery_protocol': {
'operation':
'listen',
'protocol':
'cdp'
},
'network_resource_control_version': 'version3',
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attribute is: ``name``.
Portgroup
---------
.. code-block:: python
'security_policy': {
'allow_promiscuous': true,
'mac_changes': false,
'forged_transmits': true
},
'name': 'vmotion-v702',
'out_shaping': {
'enabled': true,
'average_bandwidth': 1500,
'burst_size': 4096,
'peak_bandwidth': 1500
},
'num_ports': 128,
'teaming': {
'port_order': {
'active': [
'dvUplink2'
],
'standby': [
'dvUplink1'
]
},
'notify_switches': false,
'reverse_policy': true,
'rolling_order': false,
'policy': 'failover_explicit',
'failure_criteria': {
'check_error_percent': true,
'full_duplex': false,
'check_duplex': false,
'percentage': 50,
'check_speed': 'minimum',
'speed': 20,
'check_beacon': true
}
},
'type': 'earlyBinding',
'vlan_id': 100,
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attributes are: ``name``, ``type``.
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.7.9,
or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original ESXi State
Module was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import sys
# Import Salt Libs
import salt.exceptions
from salt.ext import six
from salt.ext.six.moves import range
# Import Third Party Libs
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return 'dvs'
def mod_init(low):
'''
Init function
'''
return True
def dvs_configured(name, dvs):
'''
Configures a DVS.
Creates a new DVS, if it doesn't exist in the provided datacenter or
reconfigures it if configured differently.
dvs
DVS dict representations (see module sysdocs)
'''
datacenter_name = _get_datacenter_name()
dvs_name = dvs['name'] if dvs.get('name') else name
log.info('Running state %s for DVS \'%s\' in datacenter \'%s\'',
name, dvs_name, datacenter_name)
changes_required = False
ret = {'name': name, 'changes': {}, 'result': None, 'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO dvs validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
dvss = __salt__['vsphere.list_dvss'](dvs_names=[dvs_name],
service_instance=si)
if not dvss:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new DVS '
'\'{1}\' in datacenter \'{2}\''
''.format(name, dvs_name, datacenter_name))
log.info(comments[-1])
else:
dvs['name'] = dvs_name
__salt__['vsphere.create_dvs'](dvs_dict=dvs,
dvs_name=dvs_name,
service_instance=si)
comments.append('Created a new DVS \'{0}\' in datacenter '
'\'{1}\''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': dvs}})
else:
# DVS already exists. Checking various aspects of the config
props = ['description', 'contact_email', 'contact_name',
'lacp_api_version', 'link_discovery_protocol',
'max_mtu', 'network_resource_control_version',
'network_resource_management_enabled']
log.trace('DVS \'%s\' found in datacenter \'%s\'. Checking '
'for any updates in %s', dvs_name, datacenter_name, props)
props_to_original_values = {}
props_to_updated_values = {}
current_dvs = dvss[0]
for prop in props:
if prop in dvs and dvs[prop] != current_dvs.get(prop):
props_to_original_values[prop] = current_dvs.get(prop)
props_to_updated_values[prop] = dvs[prop]
# Simple infrastructure traffic resource control compare doesn't
# work because num_shares is optional if share_level is not custom
# We need to do a dedicated compare for this property
infra_prop = 'infrastructure_traffic_resource_pools'
original_infra_res_pools = []
updated_infra_res_pools = []
if infra_prop in dvs:
if not current_dvs.get(infra_prop):
updated_infra_res_pools = dvs[infra_prop]
else:
for idx in range(len(dvs[infra_prop])):
if 'num_shares' not in dvs[infra_prop][idx] and \
current_dvs[infra_prop][idx]['share_level'] != \
'custom' and \
'num_shares' in current_dvs[infra_prop][idx]:
del current_dvs[infra_prop][idx]['num_shares']
if dvs[infra_prop][idx] != \
current_dvs[infra_prop][idx]:
original_infra_res_pools.append(
current_dvs[infra_prop][idx])
updated_infra_res_pools.append(
dict(dvs[infra_prop][idx]))
if updated_infra_res_pools:
props_to_original_values[
'infrastructure_traffic_resource_pools'] = \
original_infra_res_pools
props_to_updated_values[
'infrastructure_traffic_resource_pools'] = \
updated_infra_res_pools
if props_to_updated_values:
if __opts__['test']:
changes_string = ''
for p in props_to_updated_values:
if p == 'infrastructure_traffic_resource_pools':
changes_string += \
'\tinfrastructure_traffic_resource_pools:\n'
for idx in range(len(props_to_updated_values[p])):
d = props_to_updated_values[p][idx]
s = props_to_original_values[p][idx]
changes_string += \
('\t\t{0} from \'{1}\' to \'{2}\'\n'
''.format(d['key'], s, d))
else:
changes_string += \
('\t{0} from \'{1}\' to \'{2}\'\n'
''.format(p, props_to_original_values[p],
props_to_updated_values[p]))
comments.append(
'State dvs_configured will update DVS \'{0}\' '
'in datacenter \'{1}\':\n{2}'
''.format(dvs_name, datacenter_name, changes_string))
log.info(comments[-1])
else:
__salt__['vsphere.update_dvs'](
dvs_dict=props_to_updated_values,
dvs=dvs_name,
service_instance=si)
comments.append('Updated DVS \'{0}\' in datacenter \'{1}\''
''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': props_to_updated_values,
'old': props_to_original_values}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': six.text_type(exc),
'result': False if not __opts__['test'] else None})
return ret
if not comments:
# We have no changes
ret.update({'comment': ('DVS \'{0}\' in datacenter \'{1}\' is '
'correctly configured. Nothing to be done.'
''.format(dvs_name, datacenter_name)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def _get_diff_dict(dict1, dict2):
'''
Returns a dictionary with the diffs between two dictionaries
It will ignore any key that doesn't exist in dict2
'''
ret_dict = {}
for p in dict2.keys():
if p not in dict1:
ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})
elif dict1[p] != dict2[p]:
if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):
sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])
if sub_diff_dict:
ret_dict.update({p: sub_diff_dict})
else:
ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})
return ret_dict
def _get_val2_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val2 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val2' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val2']})
else:
ret_dict.update(
{p: _get_val2_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_val1_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val1 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val1' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val1']})
else:
ret_dict.update(
{p: _get_val1_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_changes_from_diff_dict(diff_dict):
'''
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
'''
changes_strings = []
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if sorted(diff_dict[p].keys()) == ['val1', 'val2']:
# Some string formatting
from_str = diff_dict[p]['val1']
if isinstance(diff_dict[p]['val1'], six.string_types):
from_str = '\'{0}\''.format(diff_dict[p]['val1'])
elif isinstance(diff_dict[p]['val1'], list):
from_str = '\'{0}\''.format(', '.join(diff_dict[p]['val1']))
to_str = diff_dict[p]['val2']
if isinstance(diff_dict[p]['val2'], six.string_types):
to_str = '\'{0}\''.format(diff_dict[p]['val2'])
elif isinstance(diff_dict[p]['val2'], list):
to_str = '\'{0}\''.format(', '.join(diff_dict[p]['val2']))
changes_strings.append('{0} from {1} to {2}'.format(
p, from_str, to_str))
else:
sub_changes = _get_changes_from_diff_dict(diff_dict[p])
if sub_changes:
changes_strings.append('{0}:'.format(p))
changes_strings.extend(['\t{0}'.format(c)
for c in sub_changes])
return changes_strings
def portgroups_configured(name, dvs, portgroups):
'''
Configures portgroups on a DVS.
Creates/updates/removes portgroups in a provided DVS
dvs
Name of the DVS
portgroups
Portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running state %s on DVS \'%s\', datacenter \'%s\'',
name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_pgs = __salt__['vsphere.list_dvportgroups'](
dvs=dvs, service_instance=si)
expected_pg_names = []
for pg in portgroups:
pg_name = pg['name']
expected_pg_names.append(pg_name)
del pg['name']
log.info('Checking pg \'%s\'', pg_name)
filtered_current_pgs = \
[p for p in current_pgs if p.get('name') == pg_name]
if not filtered_current_pgs:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new portgroup '
'\'{1}\' in DVS \'{2}\', datacenter '
'\'{3}\''.format(name, pg_name, dvs,
datacenter))
else:
__salt__['vsphere.create_dvportgroup'](
portgroup_dict=pg, portgroup_name=pg_name, dvs=dvs,
service_instance=si)
comments.append('Created a new portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update({pg_name: {'new': pg}})
else:
# Porgroup already exists. Checking the config
log.trace('Portgroup \'%s\' found in DVS \'%s\', datacenter '
'\'%s\'. Checking for any updates.',
pg_name, dvs, datacenter)
current_pg = filtered_current_pgs[0]
diff_dict = _get_diff_dict(current_pg, pg)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update portgroup \'{1}\' in '
'DVS \'{2}\', datacenter \'{3}\':\n{4}'
''.format(name, pg_name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=pg, portgroup=pg_name, dvs=dvs,
service_instance=si)
comments.append('Updated portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update(
{pg_name: {'new':
_get_val2_dict_from_diff_dict(diff_dict),
'old':
_get_val1_dict_from_diff_dict(diff_dict)}})
# Add the uplink portgroup to the expected pg names
uplink_pg = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
expected_pg_names.append(uplink_pg['name'])
# Remove any extra portgroups
for current_pg in current_pgs:
if current_pg['name'] not in expected_pg_names:
changes_required = True
if __opts__['test']:
comments.append('State {0} will remove '
'the portgroup \'{1}\' from DVS \'{2}\', '
'datacenter \'{3}\''
''.format(name, current_pg['name'], dvs,
datacenter))
else:
__salt__['vsphere.remove_dvportgroup'](
portgroup=current_pg['name'], dvs=dvs,
service_instance=si)
comments.append('Removed the portgroup \'{0}\' from DVS '
'\'{1}\', datacenter \'{2}\''
''.format(current_pg['name'], dvs,
datacenter))
log.info(comments[-1])
changes.update({current_pg['name']:
{'old': current_pg}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All portgroups in DVS \'{0}\', datacenter '
'\'{1}\' exist and are correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def uplink_portgroup_configured(name, dvs, uplink_portgroup):
'''
Configures the uplink portgroup on a DVS. The state assumes there is only
one uplink portgroup.
dvs
Name of the DVS
upling_portgroup
Uplink portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running %s on DVS \'%s\', datacenter \'%s\'', name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_uplink_portgroup = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
log.trace('current_uplink_portgroup = %s', current_uplink_portgroup)
diff_dict = _get_diff_dict(current_uplink_portgroup, uplink_portgroup)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update the '
'uplink portgroup in DVS \'{1}\', datacenter '
'\'{2}\':\n{3}'
''.format(name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=uplink_portgroup,
portgroup=current_uplink_portgroup['name'],
dvs=dvs,
service_instance=si)
comments.append('Updated the uplink portgroup in DVS '
'\'{0}\', datacenter \'{1}\''
''.format(dvs, datacenter))
log.info(comments[-1])
changes.update(
{'uplink_portgroup':
{'new': _get_val2_dict_from_diff_dict(diff_dict),
'old': _get_val1_dict_from_diff_dict(diff_dict)}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Uplink portgroup in DVS \'{0}\', datacenter '
'\'{1}\' is correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
saltstack/salt
|
salt/states/dvs.py
|
dvs_configured
|
python
|
def dvs_configured(name, dvs):
'''
Configures a DVS.
Creates a new DVS, if it doesn't exist in the provided datacenter or
reconfigures it if configured differently.
dvs
DVS dict representations (see module sysdocs)
'''
datacenter_name = _get_datacenter_name()
dvs_name = dvs['name'] if dvs.get('name') else name
log.info('Running state %s for DVS \'%s\' in datacenter \'%s\'',
name, dvs_name, datacenter_name)
changes_required = False
ret = {'name': name, 'changes': {}, 'result': None, 'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO dvs validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
dvss = __salt__['vsphere.list_dvss'](dvs_names=[dvs_name],
service_instance=si)
if not dvss:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new DVS '
'\'{1}\' in datacenter \'{2}\''
''.format(name, dvs_name, datacenter_name))
log.info(comments[-1])
else:
dvs['name'] = dvs_name
__salt__['vsphere.create_dvs'](dvs_dict=dvs,
dvs_name=dvs_name,
service_instance=si)
comments.append('Created a new DVS \'{0}\' in datacenter '
'\'{1}\''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': dvs}})
else:
# DVS already exists. Checking various aspects of the config
props = ['description', 'contact_email', 'contact_name',
'lacp_api_version', 'link_discovery_protocol',
'max_mtu', 'network_resource_control_version',
'network_resource_management_enabled']
log.trace('DVS \'%s\' found in datacenter \'%s\'. Checking '
'for any updates in %s', dvs_name, datacenter_name, props)
props_to_original_values = {}
props_to_updated_values = {}
current_dvs = dvss[0]
for prop in props:
if prop in dvs and dvs[prop] != current_dvs.get(prop):
props_to_original_values[prop] = current_dvs.get(prop)
props_to_updated_values[prop] = dvs[prop]
# Simple infrastructure traffic resource control compare doesn't
# work because num_shares is optional if share_level is not custom
# We need to do a dedicated compare for this property
infra_prop = 'infrastructure_traffic_resource_pools'
original_infra_res_pools = []
updated_infra_res_pools = []
if infra_prop in dvs:
if not current_dvs.get(infra_prop):
updated_infra_res_pools = dvs[infra_prop]
else:
for idx in range(len(dvs[infra_prop])):
if 'num_shares' not in dvs[infra_prop][idx] and \
current_dvs[infra_prop][idx]['share_level'] != \
'custom' and \
'num_shares' in current_dvs[infra_prop][idx]:
del current_dvs[infra_prop][idx]['num_shares']
if dvs[infra_prop][idx] != \
current_dvs[infra_prop][idx]:
original_infra_res_pools.append(
current_dvs[infra_prop][idx])
updated_infra_res_pools.append(
dict(dvs[infra_prop][idx]))
if updated_infra_res_pools:
props_to_original_values[
'infrastructure_traffic_resource_pools'] = \
original_infra_res_pools
props_to_updated_values[
'infrastructure_traffic_resource_pools'] = \
updated_infra_res_pools
if props_to_updated_values:
if __opts__['test']:
changes_string = ''
for p in props_to_updated_values:
if p == 'infrastructure_traffic_resource_pools':
changes_string += \
'\tinfrastructure_traffic_resource_pools:\n'
for idx in range(len(props_to_updated_values[p])):
d = props_to_updated_values[p][idx]
s = props_to_original_values[p][idx]
changes_string += \
('\t\t{0} from \'{1}\' to \'{2}\'\n'
''.format(d['key'], s, d))
else:
changes_string += \
('\t{0} from \'{1}\' to \'{2}\'\n'
''.format(p, props_to_original_values[p],
props_to_updated_values[p]))
comments.append(
'State dvs_configured will update DVS \'{0}\' '
'in datacenter \'{1}\':\n{2}'
''.format(dvs_name, datacenter_name, changes_string))
log.info(comments[-1])
else:
__salt__['vsphere.update_dvs'](
dvs_dict=props_to_updated_values,
dvs=dvs_name,
service_instance=si)
comments.append('Updated DVS \'{0}\' in datacenter \'{1}\''
''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': props_to_updated_values,
'old': props_to_original_values}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': six.text_type(exc),
'result': False if not __opts__['test'] else None})
return ret
if not comments:
# We have no changes
ret.update({'comment': ('DVS \'{0}\' in datacenter \'{1}\' is '
'correctly configured. Nothing to be done.'
''.format(dvs_name, datacenter_name)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
Configures a DVS.
Creates a new DVS, if it doesn't exist in the provided datacenter or
reconfigures it if configured differently.
dvs
DVS dict representations (see module sysdocs)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dvs.py#L264-L407
|
[
"def _get_datacenter_name():\n '''\n Returns the datacenter name configured on the proxy\n\n Supported proxies: esxcluster, esxdatacenter\n '''\n\n proxy_type = __salt__['vsphere.get_proxy_type']()\n details = None\n if proxy_type == 'esxcluster':\n details = __salt__['esxcluster.get_details']()\n elif proxy_type == 'esxdatacenter':\n details = __salt__['esxdatacenter.get_details']()\n if not details:\n raise salt.exceptions.CommandExecutionError(\n 'details for proxy type \\'{0}\\' not loaded'.format(proxy_type))\n return details['datacenter']\n"
] |
# -*- coding: utf-8 -*-
'''
Manage VMware distributed virtual switches (DVSs) and their distributed virtual
portgroups (DVportgroups).
:codeauthor: :email:`Alexandru Bleotu <alexandru.bleotu@morganstaley.com>`
Examples
========
Several settings can be changed for DVSs and DVporgroups. Here are two examples
covering all of the settings. Fewer settings can be used
DVS
---
.. code-block:: python
'name': 'dvs1',
'max_mtu': 1000,
'uplink_names': [
'dvUplink1',
'dvUplink2',
'dvUplink3'
],
'capability': {
'portgroup_operation_supported': false,
'operation_supported': true,
'port_operation_supported': false
},
'lacp_api_version': 'multipleLag',
'contact_email': 'foo@email.com',
'product_info': {
'version':
'6.0.0',
'vendor':
'VMware,
Inc.',
'name':
'DVS'
},
'network_resource_management_enabled': true,
'contact_name': 'me@email.com',
'infrastructure_traffic_resource_pools': [
{
'reservation': 0,
'limit': 1000,
'share_level': 'high',
'key': 'management',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'faultTolerance',
'num_shares': 50
},
{
'reservation': 0,
'limit': 32000,
'share_level': 'normal',
'key': 'vmotion',
'num_shares': 50
},
{
'reservation': 10000,
'limit': -1,
'share_level': 'normal',
'key': 'virtualMachine',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'custom',
'key': 'iSCSI',
'num_shares': 75
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'nfs',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'hbr',
'num_shares': 50
},
{
'reservation': 8750,
'limit': 15000,
'share_level': 'high',
'key': 'vsan',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'vdp',
'num_shares': 50
}
],
'link_discovery_protocol': {
'operation':
'listen',
'protocol':
'cdp'
},
'network_resource_control_version': 'version3',
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attribute is: ``name``.
Portgroup
---------
.. code-block:: python
'security_policy': {
'allow_promiscuous': true,
'mac_changes': false,
'forged_transmits': true
},
'name': 'vmotion-v702',
'out_shaping': {
'enabled': true,
'average_bandwidth': 1500,
'burst_size': 4096,
'peak_bandwidth': 1500
},
'num_ports': 128,
'teaming': {
'port_order': {
'active': [
'dvUplink2'
],
'standby': [
'dvUplink1'
]
},
'notify_switches': false,
'reverse_policy': true,
'rolling_order': false,
'policy': 'failover_explicit',
'failure_criteria': {
'check_error_percent': true,
'full_duplex': false,
'check_duplex': false,
'percentage': 50,
'check_speed': 'minimum',
'speed': 20,
'check_beacon': true
}
},
'type': 'earlyBinding',
'vlan_id': 100,
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attributes are: ``name``, ``type``.
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.7.9,
or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original ESXi State
Module was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import sys
# Import Salt Libs
import salt.exceptions
from salt.ext import six
from salt.ext.six.moves import range
# Import Third Party Libs
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return 'dvs'
def mod_init(low):
'''
Init function
'''
return True
def _get_datacenter_name():
'''
Returns the datacenter name configured on the proxy
Supported proxies: esxcluster, esxdatacenter
'''
proxy_type = __salt__['vsphere.get_proxy_type']()
details = None
if proxy_type == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxy_type == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
if not details:
raise salt.exceptions.CommandExecutionError(
'details for proxy type \'{0}\' not loaded'.format(proxy_type))
return details['datacenter']
def _get_diff_dict(dict1, dict2):
'''
Returns a dictionary with the diffs between two dictionaries
It will ignore any key that doesn't exist in dict2
'''
ret_dict = {}
for p in dict2.keys():
if p not in dict1:
ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})
elif dict1[p] != dict2[p]:
if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):
sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])
if sub_diff_dict:
ret_dict.update({p: sub_diff_dict})
else:
ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})
return ret_dict
def _get_val2_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val2 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val2' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val2']})
else:
ret_dict.update(
{p: _get_val2_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_val1_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val1 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val1' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val1']})
else:
ret_dict.update(
{p: _get_val1_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_changes_from_diff_dict(diff_dict):
'''
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
'''
changes_strings = []
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if sorted(diff_dict[p].keys()) == ['val1', 'val2']:
# Some string formatting
from_str = diff_dict[p]['val1']
if isinstance(diff_dict[p]['val1'], six.string_types):
from_str = '\'{0}\''.format(diff_dict[p]['val1'])
elif isinstance(diff_dict[p]['val1'], list):
from_str = '\'{0}\''.format(', '.join(diff_dict[p]['val1']))
to_str = diff_dict[p]['val2']
if isinstance(diff_dict[p]['val2'], six.string_types):
to_str = '\'{0}\''.format(diff_dict[p]['val2'])
elif isinstance(diff_dict[p]['val2'], list):
to_str = '\'{0}\''.format(', '.join(diff_dict[p]['val2']))
changes_strings.append('{0} from {1} to {2}'.format(
p, from_str, to_str))
else:
sub_changes = _get_changes_from_diff_dict(diff_dict[p])
if sub_changes:
changes_strings.append('{0}:'.format(p))
changes_strings.extend(['\t{0}'.format(c)
for c in sub_changes])
return changes_strings
def portgroups_configured(name, dvs, portgroups):
'''
Configures portgroups on a DVS.
Creates/updates/removes portgroups in a provided DVS
dvs
Name of the DVS
portgroups
Portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running state %s on DVS \'%s\', datacenter \'%s\'',
name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_pgs = __salt__['vsphere.list_dvportgroups'](
dvs=dvs, service_instance=si)
expected_pg_names = []
for pg in portgroups:
pg_name = pg['name']
expected_pg_names.append(pg_name)
del pg['name']
log.info('Checking pg \'%s\'', pg_name)
filtered_current_pgs = \
[p for p in current_pgs if p.get('name') == pg_name]
if not filtered_current_pgs:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new portgroup '
'\'{1}\' in DVS \'{2}\', datacenter '
'\'{3}\''.format(name, pg_name, dvs,
datacenter))
else:
__salt__['vsphere.create_dvportgroup'](
portgroup_dict=pg, portgroup_name=pg_name, dvs=dvs,
service_instance=si)
comments.append('Created a new portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update({pg_name: {'new': pg}})
else:
# Porgroup already exists. Checking the config
log.trace('Portgroup \'%s\' found in DVS \'%s\', datacenter '
'\'%s\'. Checking for any updates.',
pg_name, dvs, datacenter)
current_pg = filtered_current_pgs[0]
diff_dict = _get_diff_dict(current_pg, pg)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update portgroup \'{1}\' in '
'DVS \'{2}\', datacenter \'{3}\':\n{4}'
''.format(name, pg_name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=pg, portgroup=pg_name, dvs=dvs,
service_instance=si)
comments.append('Updated portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update(
{pg_name: {'new':
_get_val2_dict_from_diff_dict(diff_dict),
'old':
_get_val1_dict_from_diff_dict(diff_dict)}})
# Add the uplink portgroup to the expected pg names
uplink_pg = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
expected_pg_names.append(uplink_pg['name'])
# Remove any extra portgroups
for current_pg in current_pgs:
if current_pg['name'] not in expected_pg_names:
changes_required = True
if __opts__['test']:
comments.append('State {0} will remove '
'the portgroup \'{1}\' from DVS \'{2}\', '
'datacenter \'{3}\''
''.format(name, current_pg['name'], dvs,
datacenter))
else:
__salt__['vsphere.remove_dvportgroup'](
portgroup=current_pg['name'], dvs=dvs,
service_instance=si)
comments.append('Removed the portgroup \'{0}\' from DVS '
'\'{1}\', datacenter \'{2}\''
''.format(current_pg['name'], dvs,
datacenter))
log.info(comments[-1])
changes.update({current_pg['name']:
{'old': current_pg}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All portgroups in DVS \'{0}\', datacenter '
'\'{1}\' exist and are correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def uplink_portgroup_configured(name, dvs, uplink_portgroup):
'''
Configures the uplink portgroup on a DVS. The state assumes there is only
one uplink portgroup.
dvs
Name of the DVS
upling_portgroup
Uplink portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running %s on DVS \'%s\', datacenter \'%s\'', name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_uplink_portgroup = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
log.trace('current_uplink_portgroup = %s', current_uplink_portgroup)
diff_dict = _get_diff_dict(current_uplink_portgroup, uplink_portgroup)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update the '
'uplink portgroup in DVS \'{1}\', datacenter '
'\'{2}\':\n{3}'
''.format(name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=uplink_portgroup,
portgroup=current_uplink_portgroup['name'],
dvs=dvs,
service_instance=si)
comments.append('Updated the uplink portgroup in DVS '
'\'{0}\', datacenter \'{1}\''
''.format(dvs, datacenter))
log.info(comments[-1])
changes.update(
{'uplink_portgroup':
{'new': _get_val2_dict_from_diff_dict(diff_dict),
'old': _get_val1_dict_from_diff_dict(diff_dict)}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Uplink portgroup in DVS \'{0}\', datacenter '
'\'{1}\' is correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
saltstack/salt
|
salt/states/dvs.py
|
_get_diff_dict
|
python
|
def _get_diff_dict(dict1, dict2):
'''
Returns a dictionary with the diffs between two dictionaries
It will ignore any key that doesn't exist in dict2
'''
ret_dict = {}
for p in dict2.keys():
if p not in dict1:
ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})
elif dict1[p] != dict2[p]:
if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):
sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])
if sub_diff_dict:
ret_dict.update({p: sub_diff_dict})
else:
ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})
return ret_dict
|
Returns a dictionary with the diffs between two dictionaries
It will ignore any key that doesn't exist in dict2
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dvs.py#L410-L427
|
[
"def _get_diff_dict(dict1, dict2):\n '''\n Returns a dictionary with the diffs between two dictionaries\n\n It will ignore any key that doesn't exist in dict2\n '''\n ret_dict = {}\n for p in dict2.keys():\n if p not in dict1:\n ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})\n elif dict1[p] != dict2[p]:\n if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):\n sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])\n if sub_diff_dict:\n ret_dict.update({p: sub_diff_dict})\n else:\n ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})\n return ret_dict\n"
] |
# -*- coding: utf-8 -*-
'''
Manage VMware distributed virtual switches (DVSs) and their distributed virtual
portgroups (DVportgroups).
:codeauthor: :email:`Alexandru Bleotu <alexandru.bleotu@morganstaley.com>`
Examples
========
Several settings can be changed for DVSs and DVporgroups. Here are two examples
covering all of the settings. Fewer settings can be used
DVS
---
.. code-block:: python
'name': 'dvs1',
'max_mtu': 1000,
'uplink_names': [
'dvUplink1',
'dvUplink2',
'dvUplink3'
],
'capability': {
'portgroup_operation_supported': false,
'operation_supported': true,
'port_operation_supported': false
},
'lacp_api_version': 'multipleLag',
'contact_email': 'foo@email.com',
'product_info': {
'version':
'6.0.0',
'vendor':
'VMware,
Inc.',
'name':
'DVS'
},
'network_resource_management_enabled': true,
'contact_name': 'me@email.com',
'infrastructure_traffic_resource_pools': [
{
'reservation': 0,
'limit': 1000,
'share_level': 'high',
'key': 'management',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'faultTolerance',
'num_shares': 50
},
{
'reservation': 0,
'limit': 32000,
'share_level': 'normal',
'key': 'vmotion',
'num_shares': 50
},
{
'reservation': 10000,
'limit': -1,
'share_level': 'normal',
'key': 'virtualMachine',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'custom',
'key': 'iSCSI',
'num_shares': 75
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'nfs',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'hbr',
'num_shares': 50
},
{
'reservation': 8750,
'limit': 15000,
'share_level': 'high',
'key': 'vsan',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'vdp',
'num_shares': 50
}
],
'link_discovery_protocol': {
'operation':
'listen',
'protocol':
'cdp'
},
'network_resource_control_version': 'version3',
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attribute is: ``name``.
Portgroup
---------
.. code-block:: python
'security_policy': {
'allow_promiscuous': true,
'mac_changes': false,
'forged_transmits': true
},
'name': 'vmotion-v702',
'out_shaping': {
'enabled': true,
'average_bandwidth': 1500,
'burst_size': 4096,
'peak_bandwidth': 1500
},
'num_ports': 128,
'teaming': {
'port_order': {
'active': [
'dvUplink2'
],
'standby': [
'dvUplink1'
]
},
'notify_switches': false,
'reverse_policy': true,
'rolling_order': false,
'policy': 'failover_explicit',
'failure_criteria': {
'check_error_percent': true,
'full_duplex': false,
'check_duplex': false,
'percentage': 50,
'check_speed': 'minimum',
'speed': 20,
'check_beacon': true
}
},
'type': 'earlyBinding',
'vlan_id': 100,
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attributes are: ``name``, ``type``.
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.7.9,
or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original ESXi State
Module was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import sys
# Import Salt Libs
import salt.exceptions
from salt.ext import six
from salt.ext.six.moves import range
# Import Third Party Libs
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return 'dvs'
def mod_init(low):
'''
Init function
'''
return True
def _get_datacenter_name():
'''
Returns the datacenter name configured on the proxy
Supported proxies: esxcluster, esxdatacenter
'''
proxy_type = __salt__['vsphere.get_proxy_type']()
details = None
if proxy_type == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxy_type == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
if not details:
raise salt.exceptions.CommandExecutionError(
'details for proxy type \'{0}\' not loaded'.format(proxy_type))
return details['datacenter']
def dvs_configured(name, dvs):
'''
Configures a DVS.
Creates a new DVS, if it doesn't exist in the provided datacenter or
reconfigures it if configured differently.
dvs
DVS dict representations (see module sysdocs)
'''
datacenter_name = _get_datacenter_name()
dvs_name = dvs['name'] if dvs.get('name') else name
log.info('Running state %s for DVS \'%s\' in datacenter \'%s\'',
name, dvs_name, datacenter_name)
changes_required = False
ret = {'name': name, 'changes': {}, 'result': None, 'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO dvs validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
dvss = __salt__['vsphere.list_dvss'](dvs_names=[dvs_name],
service_instance=si)
if not dvss:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new DVS '
'\'{1}\' in datacenter \'{2}\''
''.format(name, dvs_name, datacenter_name))
log.info(comments[-1])
else:
dvs['name'] = dvs_name
__salt__['vsphere.create_dvs'](dvs_dict=dvs,
dvs_name=dvs_name,
service_instance=si)
comments.append('Created a new DVS \'{0}\' in datacenter '
'\'{1}\''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': dvs}})
else:
# DVS already exists. Checking various aspects of the config
props = ['description', 'contact_email', 'contact_name',
'lacp_api_version', 'link_discovery_protocol',
'max_mtu', 'network_resource_control_version',
'network_resource_management_enabled']
log.trace('DVS \'%s\' found in datacenter \'%s\'. Checking '
'for any updates in %s', dvs_name, datacenter_name, props)
props_to_original_values = {}
props_to_updated_values = {}
current_dvs = dvss[0]
for prop in props:
if prop in dvs and dvs[prop] != current_dvs.get(prop):
props_to_original_values[prop] = current_dvs.get(prop)
props_to_updated_values[prop] = dvs[prop]
# Simple infrastructure traffic resource control compare doesn't
# work because num_shares is optional if share_level is not custom
# We need to do a dedicated compare for this property
infra_prop = 'infrastructure_traffic_resource_pools'
original_infra_res_pools = []
updated_infra_res_pools = []
if infra_prop in dvs:
if not current_dvs.get(infra_prop):
updated_infra_res_pools = dvs[infra_prop]
else:
for idx in range(len(dvs[infra_prop])):
if 'num_shares' not in dvs[infra_prop][idx] and \
current_dvs[infra_prop][idx]['share_level'] != \
'custom' and \
'num_shares' in current_dvs[infra_prop][idx]:
del current_dvs[infra_prop][idx]['num_shares']
if dvs[infra_prop][idx] != \
current_dvs[infra_prop][idx]:
original_infra_res_pools.append(
current_dvs[infra_prop][idx])
updated_infra_res_pools.append(
dict(dvs[infra_prop][idx]))
if updated_infra_res_pools:
props_to_original_values[
'infrastructure_traffic_resource_pools'] = \
original_infra_res_pools
props_to_updated_values[
'infrastructure_traffic_resource_pools'] = \
updated_infra_res_pools
if props_to_updated_values:
if __opts__['test']:
changes_string = ''
for p in props_to_updated_values:
if p == 'infrastructure_traffic_resource_pools':
changes_string += \
'\tinfrastructure_traffic_resource_pools:\n'
for idx in range(len(props_to_updated_values[p])):
d = props_to_updated_values[p][idx]
s = props_to_original_values[p][idx]
changes_string += \
('\t\t{0} from \'{1}\' to \'{2}\'\n'
''.format(d['key'], s, d))
else:
changes_string += \
('\t{0} from \'{1}\' to \'{2}\'\n'
''.format(p, props_to_original_values[p],
props_to_updated_values[p]))
comments.append(
'State dvs_configured will update DVS \'{0}\' '
'in datacenter \'{1}\':\n{2}'
''.format(dvs_name, datacenter_name, changes_string))
log.info(comments[-1])
else:
__salt__['vsphere.update_dvs'](
dvs_dict=props_to_updated_values,
dvs=dvs_name,
service_instance=si)
comments.append('Updated DVS \'{0}\' in datacenter \'{1}\''
''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': props_to_updated_values,
'old': props_to_original_values}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': six.text_type(exc),
'result': False if not __opts__['test'] else None})
return ret
if not comments:
# We have no changes
ret.update({'comment': ('DVS \'{0}\' in datacenter \'{1}\' is '
'correctly configured. Nothing to be done.'
''.format(dvs_name, datacenter_name)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def _get_val2_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val2 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val2' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val2']})
else:
ret_dict.update(
{p: _get_val2_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_val1_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val1 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val1' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val1']})
else:
ret_dict.update(
{p: _get_val1_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_changes_from_diff_dict(diff_dict):
'''
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
'''
changes_strings = []
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if sorted(diff_dict[p].keys()) == ['val1', 'val2']:
# Some string formatting
from_str = diff_dict[p]['val1']
if isinstance(diff_dict[p]['val1'], six.string_types):
from_str = '\'{0}\''.format(diff_dict[p]['val1'])
elif isinstance(diff_dict[p]['val1'], list):
from_str = '\'{0}\''.format(', '.join(diff_dict[p]['val1']))
to_str = diff_dict[p]['val2']
if isinstance(diff_dict[p]['val2'], six.string_types):
to_str = '\'{0}\''.format(diff_dict[p]['val2'])
elif isinstance(diff_dict[p]['val2'], list):
to_str = '\'{0}\''.format(', '.join(diff_dict[p]['val2']))
changes_strings.append('{0} from {1} to {2}'.format(
p, from_str, to_str))
else:
sub_changes = _get_changes_from_diff_dict(diff_dict[p])
if sub_changes:
changes_strings.append('{0}:'.format(p))
changes_strings.extend(['\t{0}'.format(c)
for c in sub_changes])
return changes_strings
def portgroups_configured(name, dvs, portgroups):
'''
Configures portgroups on a DVS.
Creates/updates/removes portgroups in a provided DVS
dvs
Name of the DVS
portgroups
Portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running state %s on DVS \'%s\', datacenter \'%s\'',
name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_pgs = __salt__['vsphere.list_dvportgroups'](
dvs=dvs, service_instance=si)
expected_pg_names = []
for pg in portgroups:
pg_name = pg['name']
expected_pg_names.append(pg_name)
del pg['name']
log.info('Checking pg \'%s\'', pg_name)
filtered_current_pgs = \
[p for p in current_pgs if p.get('name') == pg_name]
if not filtered_current_pgs:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new portgroup '
'\'{1}\' in DVS \'{2}\', datacenter '
'\'{3}\''.format(name, pg_name, dvs,
datacenter))
else:
__salt__['vsphere.create_dvportgroup'](
portgroup_dict=pg, portgroup_name=pg_name, dvs=dvs,
service_instance=si)
comments.append('Created a new portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update({pg_name: {'new': pg}})
else:
# Porgroup already exists. Checking the config
log.trace('Portgroup \'%s\' found in DVS \'%s\', datacenter '
'\'%s\'. Checking for any updates.',
pg_name, dvs, datacenter)
current_pg = filtered_current_pgs[0]
diff_dict = _get_diff_dict(current_pg, pg)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update portgroup \'{1}\' in '
'DVS \'{2}\', datacenter \'{3}\':\n{4}'
''.format(name, pg_name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=pg, portgroup=pg_name, dvs=dvs,
service_instance=si)
comments.append('Updated portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update(
{pg_name: {'new':
_get_val2_dict_from_diff_dict(diff_dict),
'old':
_get_val1_dict_from_diff_dict(diff_dict)}})
# Add the uplink portgroup to the expected pg names
uplink_pg = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
expected_pg_names.append(uplink_pg['name'])
# Remove any extra portgroups
for current_pg in current_pgs:
if current_pg['name'] not in expected_pg_names:
changes_required = True
if __opts__['test']:
comments.append('State {0} will remove '
'the portgroup \'{1}\' from DVS \'{2}\', '
'datacenter \'{3}\''
''.format(name, current_pg['name'], dvs,
datacenter))
else:
__salt__['vsphere.remove_dvportgroup'](
portgroup=current_pg['name'], dvs=dvs,
service_instance=si)
comments.append('Removed the portgroup \'{0}\' from DVS '
'\'{1}\', datacenter \'{2}\''
''.format(current_pg['name'], dvs,
datacenter))
log.info(comments[-1])
changes.update({current_pg['name']:
{'old': current_pg}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All portgroups in DVS \'{0}\', datacenter '
'\'{1}\' exist and are correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def uplink_portgroup_configured(name, dvs, uplink_portgroup):
'''
Configures the uplink portgroup on a DVS. The state assumes there is only
one uplink portgroup.
dvs
Name of the DVS
upling_portgroup
Uplink portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running %s on DVS \'%s\', datacenter \'%s\'', name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_uplink_portgroup = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
log.trace('current_uplink_portgroup = %s', current_uplink_portgroup)
diff_dict = _get_diff_dict(current_uplink_portgroup, uplink_portgroup)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update the '
'uplink portgroup in DVS \'{1}\', datacenter '
'\'{2}\':\n{3}'
''.format(name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=uplink_portgroup,
portgroup=current_uplink_portgroup['name'],
dvs=dvs,
service_instance=si)
comments.append('Updated the uplink portgroup in DVS '
'\'{0}\', datacenter \'{1}\''
''.format(dvs, datacenter))
log.info(comments[-1])
changes.update(
{'uplink_portgroup':
{'new': _get_val2_dict_from_diff_dict(diff_dict),
'old': _get_val1_dict_from_diff_dict(diff_dict)}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Uplink portgroup in DVS \'{0}\', datacenter '
'\'{1}\' is correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
saltstack/salt
|
salt/states/dvs.py
|
_get_val2_dict_from_diff_dict
|
python
|
def _get_val2_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val2 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val2' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val2']})
else:
ret_dict.update(
{p: _get_val2_dict_from_diff_dict(diff_dict[p])})
return ret_dict
|
Returns a dictionaries with the values stored in val2 of a diff dict.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dvs.py#L430-L443
|
[
"def _get_val2_dict_from_diff_dict(diff_dict):\n '''\n Returns a dictionaries with the values stored in val2 of a diff dict.\n '''\n ret_dict = {}\n for p in diff_dict.keys():\n if not isinstance(diff_dict[p], dict):\n raise ValueError('Unexpected diff difct \\'{0}\\''.format(diff_dict))\n if 'val2' in diff_dict[p].keys():\n ret_dict.update({p: diff_dict[p]['val2']})\n else:\n ret_dict.update(\n {p: _get_val2_dict_from_diff_dict(diff_dict[p])})\n return ret_dict\n"
] |
# -*- coding: utf-8 -*-
'''
Manage VMware distributed virtual switches (DVSs) and their distributed virtual
portgroups (DVportgroups).
:codeauthor: :email:`Alexandru Bleotu <alexandru.bleotu@morganstaley.com>`
Examples
========
Several settings can be changed for DVSs and DVporgroups. Here are two examples
covering all of the settings. Fewer settings can be used
DVS
---
.. code-block:: python
'name': 'dvs1',
'max_mtu': 1000,
'uplink_names': [
'dvUplink1',
'dvUplink2',
'dvUplink3'
],
'capability': {
'portgroup_operation_supported': false,
'operation_supported': true,
'port_operation_supported': false
},
'lacp_api_version': 'multipleLag',
'contact_email': 'foo@email.com',
'product_info': {
'version':
'6.0.0',
'vendor':
'VMware,
Inc.',
'name':
'DVS'
},
'network_resource_management_enabled': true,
'contact_name': 'me@email.com',
'infrastructure_traffic_resource_pools': [
{
'reservation': 0,
'limit': 1000,
'share_level': 'high',
'key': 'management',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'faultTolerance',
'num_shares': 50
},
{
'reservation': 0,
'limit': 32000,
'share_level': 'normal',
'key': 'vmotion',
'num_shares': 50
},
{
'reservation': 10000,
'limit': -1,
'share_level': 'normal',
'key': 'virtualMachine',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'custom',
'key': 'iSCSI',
'num_shares': 75
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'nfs',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'hbr',
'num_shares': 50
},
{
'reservation': 8750,
'limit': 15000,
'share_level': 'high',
'key': 'vsan',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'vdp',
'num_shares': 50
}
],
'link_discovery_protocol': {
'operation':
'listen',
'protocol':
'cdp'
},
'network_resource_control_version': 'version3',
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attribute is: ``name``.
Portgroup
---------
.. code-block:: python
'security_policy': {
'allow_promiscuous': true,
'mac_changes': false,
'forged_transmits': true
},
'name': 'vmotion-v702',
'out_shaping': {
'enabled': true,
'average_bandwidth': 1500,
'burst_size': 4096,
'peak_bandwidth': 1500
},
'num_ports': 128,
'teaming': {
'port_order': {
'active': [
'dvUplink2'
],
'standby': [
'dvUplink1'
]
},
'notify_switches': false,
'reverse_policy': true,
'rolling_order': false,
'policy': 'failover_explicit',
'failure_criteria': {
'check_error_percent': true,
'full_duplex': false,
'check_duplex': false,
'percentage': 50,
'check_speed': 'minimum',
'speed': 20,
'check_beacon': true
}
},
'type': 'earlyBinding',
'vlan_id': 100,
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attributes are: ``name``, ``type``.
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.7.9,
or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original ESXi State
Module was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import sys
# Import Salt Libs
import salt.exceptions
from salt.ext import six
from salt.ext.six.moves import range
# Import Third Party Libs
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return 'dvs'
def mod_init(low):
'''
Init function
'''
return True
def _get_datacenter_name():
'''
Returns the datacenter name configured on the proxy
Supported proxies: esxcluster, esxdatacenter
'''
proxy_type = __salt__['vsphere.get_proxy_type']()
details = None
if proxy_type == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxy_type == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
if not details:
raise salt.exceptions.CommandExecutionError(
'details for proxy type \'{0}\' not loaded'.format(proxy_type))
return details['datacenter']
def dvs_configured(name, dvs):
'''
Configures a DVS.
Creates a new DVS, if it doesn't exist in the provided datacenter or
reconfigures it if configured differently.
dvs
DVS dict representations (see module sysdocs)
'''
datacenter_name = _get_datacenter_name()
dvs_name = dvs['name'] if dvs.get('name') else name
log.info('Running state %s for DVS \'%s\' in datacenter \'%s\'',
name, dvs_name, datacenter_name)
changes_required = False
ret = {'name': name, 'changes': {}, 'result': None, 'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO dvs validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
dvss = __salt__['vsphere.list_dvss'](dvs_names=[dvs_name],
service_instance=si)
if not dvss:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new DVS '
'\'{1}\' in datacenter \'{2}\''
''.format(name, dvs_name, datacenter_name))
log.info(comments[-1])
else:
dvs['name'] = dvs_name
__salt__['vsphere.create_dvs'](dvs_dict=dvs,
dvs_name=dvs_name,
service_instance=si)
comments.append('Created a new DVS \'{0}\' in datacenter '
'\'{1}\''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': dvs}})
else:
# DVS already exists. Checking various aspects of the config
props = ['description', 'contact_email', 'contact_name',
'lacp_api_version', 'link_discovery_protocol',
'max_mtu', 'network_resource_control_version',
'network_resource_management_enabled']
log.trace('DVS \'%s\' found in datacenter \'%s\'. Checking '
'for any updates in %s', dvs_name, datacenter_name, props)
props_to_original_values = {}
props_to_updated_values = {}
current_dvs = dvss[0]
for prop in props:
if prop in dvs and dvs[prop] != current_dvs.get(prop):
props_to_original_values[prop] = current_dvs.get(prop)
props_to_updated_values[prop] = dvs[prop]
# Simple infrastructure traffic resource control compare doesn't
# work because num_shares is optional if share_level is not custom
# We need to do a dedicated compare for this property
infra_prop = 'infrastructure_traffic_resource_pools'
original_infra_res_pools = []
updated_infra_res_pools = []
if infra_prop in dvs:
if not current_dvs.get(infra_prop):
updated_infra_res_pools = dvs[infra_prop]
else:
for idx in range(len(dvs[infra_prop])):
if 'num_shares' not in dvs[infra_prop][idx] and \
current_dvs[infra_prop][idx]['share_level'] != \
'custom' and \
'num_shares' in current_dvs[infra_prop][idx]:
del current_dvs[infra_prop][idx]['num_shares']
if dvs[infra_prop][idx] != \
current_dvs[infra_prop][idx]:
original_infra_res_pools.append(
current_dvs[infra_prop][idx])
updated_infra_res_pools.append(
dict(dvs[infra_prop][idx]))
if updated_infra_res_pools:
props_to_original_values[
'infrastructure_traffic_resource_pools'] = \
original_infra_res_pools
props_to_updated_values[
'infrastructure_traffic_resource_pools'] = \
updated_infra_res_pools
if props_to_updated_values:
if __opts__['test']:
changes_string = ''
for p in props_to_updated_values:
if p == 'infrastructure_traffic_resource_pools':
changes_string += \
'\tinfrastructure_traffic_resource_pools:\n'
for idx in range(len(props_to_updated_values[p])):
d = props_to_updated_values[p][idx]
s = props_to_original_values[p][idx]
changes_string += \
('\t\t{0} from \'{1}\' to \'{2}\'\n'
''.format(d['key'], s, d))
else:
changes_string += \
('\t{0} from \'{1}\' to \'{2}\'\n'
''.format(p, props_to_original_values[p],
props_to_updated_values[p]))
comments.append(
'State dvs_configured will update DVS \'{0}\' '
'in datacenter \'{1}\':\n{2}'
''.format(dvs_name, datacenter_name, changes_string))
log.info(comments[-1])
else:
__salt__['vsphere.update_dvs'](
dvs_dict=props_to_updated_values,
dvs=dvs_name,
service_instance=si)
comments.append('Updated DVS \'{0}\' in datacenter \'{1}\''
''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': props_to_updated_values,
'old': props_to_original_values}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': six.text_type(exc),
'result': False if not __opts__['test'] else None})
return ret
if not comments:
# We have no changes
ret.update({'comment': ('DVS \'{0}\' in datacenter \'{1}\' is '
'correctly configured. Nothing to be done.'
''.format(dvs_name, datacenter_name)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def _get_diff_dict(dict1, dict2):
'''
Returns a dictionary with the diffs between two dictionaries
It will ignore any key that doesn't exist in dict2
'''
ret_dict = {}
for p in dict2.keys():
if p not in dict1:
ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})
elif dict1[p] != dict2[p]:
if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):
sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])
if sub_diff_dict:
ret_dict.update({p: sub_diff_dict})
else:
ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})
return ret_dict
def _get_val1_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val1 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val1' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val1']})
else:
ret_dict.update(
{p: _get_val1_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_changes_from_diff_dict(diff_dict):
'''
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
'''
changes_strings = []
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if sorted(diff_dict[p].keys()) == ['val1', 'val2']:
# Some string formatting
from_str = diff_dict[p]['val1']
if isinstance(diff_dict[p]['val1'], six.string_types):
from_str = '\'{0}\''.format(diff_dict[p]['val1'])
elif isinstance(diff_dict[p]['val1'], list):
from_str = '\'{0}\''.format(', '.join(diff_dict[p]['val1']))
to_str = diff_dict[p]['val2']
if isinstance(diff_dict[p]['val2'], six.string_types):
to_str = '\'{0}\''.format(diff_dict[p]['val2'])
elif isinstance(diff_dict[p]['val2'], list):
to_str = '\'{0}\''.format(', '.join(diff_dict[p]['val2']))
changes_strings.append('{0} from {1} to {2}'.format(
p, from_str, to_str))
else:
sub_changes = _get_changes_from_diff_dict(diff_dict[p])
if sub_changes:
changes_strings.append('{0}:'.format(p))
changes_strings.extend(['\t{0}'.format(c)
for c in sub_changes])
return changes_strings
def portgroups_configured(name, dvs, portgroups):
'''
Configures portgroups on a DVS.
Creates/updates/removes portgroups in a provided DVS
dvs
Name of the DVS
portgroups
Portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running state %s on DVS \'%s\', datacenter \'%s\'',
name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_pgs = __salt__['vsphere.list_dvportgroups'](
dvs=dvs, service_instance=si)
expected_pg_names = []
for pg in portgroups:
pg_name = pg['name']
expected_pg_names.append(pg_name)
del pg['name']
log.info('Checking pg \'%s\'', pg_name)
filtered_current_pgs = \
[p for p in current_pgs if p.get('name') == pg_name]
if not filtered_current_pgs:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new portgroup '
'\'{1}\' in DVS \'{2}\', datacenter '
'\'{3}\''.format(name, pg_name, dvs,
datacenter))
else:
__salt__['vsphere.create_dvportgroup'](
portgroup_dict=pg, portgroup_name=pg_name, dvs=dvs,
service_instance=si)
comments.append('Created a new portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update({pg_name: {'new': pg}})
else:
# Porgroup already exists. Checking the config
log.trace('Portgroup \'%s\' found in DVS \'%s\', datacenter '
'\'%s\'. Checking for any updates.',
pg_name, dvs, datacenter)
current_pg = filtered_current_pgs[0]
diff_dict = _get_diff_dict(current_pg, pg)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update portgroup \'{1}\' in '
'DVS \'{2}\', datacenter \'{3}\':\n{4}'
''.format(name, pg_name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=pg, portgroup=pg_name, dvs=dvs,
service_instance=si)
comments.append('Updated portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update(
{pg_name: {'new':
_get_val2_dict_from_diff_dict(diff_dict),
'old':
_get_val1_dict_from_diff_dict(diff_dict)}})
# Add the uplink portgroup to the expected pg names
uplink_pg = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
expected_pg_names.append(uplink_pg['name'])
# Remove any extra portgroups
for current_pg in current_pgs:
if current_pg['name'] not in expected_pg_names:
changes_required = True
if __opts__['test']:
comments.append('State {0} will remove '
'the portgroup \'{1}\' from DVS \'{2}\', '
'datacenter \'{3}\''
''.format(name, current_pg['name'], dvs,
datacenter))
else:
__salt__['vsphere.remove_dvportgroup'](
portgroup=current_pg['name'], dvs=dvs,
service_instance=si)
comments.append('Removed the portgroup \'{0}\' from DVS '
'\'{1}\', datacenter \'{2}\''
''.format(current_pg['name'], dvs,
datacenter))
log.info(comments[-1])
changes.update({current_pg['name']:
{'old': current_pg}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All portgroups in DVS \'{0}\', datacenter '
'\'{1}\' exist and are correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def uplink_portgroup_configured(name, dvs, uplink_portgroup):
'''
Configures the uplink portgroup on a DVS. The state assumes there is only
one uplink portgroup.
dvs
Name of the DVS
upling_portgroup
Uplink portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running %s on DVS \'%s\', datacenter \'%s\'', name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_uplink_portgroup = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
log.trace('current_uplink_portgroup = %s', current_uplink_portgroup)
diff_dict = _get_diff_dict(current_uplink_portgroup, uplink_portgroup)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update the '
'uplink portgroup in DVS \'{1}\', datacenter '
'\'{2}\':\n{3}'
''.format(name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=uplink_portgroup,
portgroup=current_uplink_portgroup['name'],
dvs=dvs,
service_instance=si)
comments.append('Updated the uplink portgroup in DVS '
'\'{0}\', datacenter \'{1}\''
''.format(dvs, datacenter))
log.info(comments[-1])
changes.update(
{'uplink_portgroup':
{'new': _get_val2_dict_from_diff_dict(diff_dict),
'old': _get_val1_dict_from_diff_dict(diff_dict)}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Uplink portgroup in DVS \'{0}\', datacenter '
'\'{1}\' is correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
saltstack/salt
|
salt/states/dvs.py
|
_get_changes_from_diff_dict
|
python
|
def _get_changes_from_diff_dict(diff_dict):
'''
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
'''
changes_strings = []
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if sorted(diff_dict[p].keys()) == ['val1', 'val2']:
# Some string formatting
from_str = diff_dict[p]['val1']
if isinstance(diff_dict[p]['val1'], six.string_types):
from_str = '\'{0}\''.format(diff_dict[p]['val1'])
elif isinstance(diff_dict[p]['val1'], list):
from_str = '\'{0}\''.format(', '.join(diff_dict[p]['val1']))
to_str = diff_dict[p]['val2']
if isinstance(diff_dict[p]['val2'], six.string_types):
to_str = '\'{0}\''.format(diff_dict[p]['val2'])
elif isinstance(diff_dict[p]['val2'], list):
to_str = '\'{0}\''.format(', '.join(diff_dict[p]['val2']))
changes_strings.append('{0} from {1} to {2}'.format(
p, from_str, to_str))
else:
sub_changes = _get_changes_from_diff_dict(diff_dict[p])
if sub_changes:
changes_strings.append('{0}:'.format(p))
changes_strings.extend(['\t{0}'.format(c)
for c in sub_changes])
return changes_strings
|
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dvs.py#L462-L492
|
[
"def _get_changes_from_diff_dict(diff_dict):\n '''\n Returns a list of string message of the differences in a diff dict.\n\n Each inner message is tabulated one tab deeper\n '''\n changes_strings = []\n for p in diff_dict.keys():\n if not isinstance(diff_dict[p], dict):\n raise ValueError('Unexpected diff difct \\'{0}\\''.format(diff_dict))\n if sorted(diff_dict[p].keys()) == ['val1', 'val2']:\n # Some string formatting\n from_str = diff_dict[p]['val1']\n if isinstance(diff_dict[p]['val1'], six.string_types):\n from_str = '\\'{0}\\''.format(diff_dict[p]['val1'])\n elif isinstance(diff_dict[p]['val1'], list):\n from_str = '\\'{0}\\''.format(', '.join(diff_dict[p]['val1']))\n to_str = diff_dict[p]['val2']\n if isinstance(diff_dict[p]['val2'], six.string_types):\n to_str = '\\'{0}\\''.format(diff_dict[p]['val2'])\n elif isinstance(diff_dict[p]['val2'], list):\n to_str = '\\'{0}\\''.format(', '.join(diff_dict[p]['val2']))\n changes_strings.append('{0} from {1} to {2}'.format(\n p, from_str, to_str))\n else:\n sub_changes = _get_changes_from_diff_dict(diff_dict[p])\n if sub_changes:\n changes_strings.append('{0}:'.format(p))\n changes_strings.extend(['\\t{0}'.format(c)\n for c in sub_changes])\n return changes_strings\n"
] |
# -*- coding: utf-8 -*-
'''
Manage VMware distributed virtual switches (DVSs) and their distributed virtual
portgroups (DVportgroups).
:codeauthor: :email:`Alexandru Bleotu <alexandru.bleotu@morganstaley.com>`
Examples
========
Several settings can be changed for DVSs and DVporgroups. Here are two examples
covering all of the settings. Fewer settings can be used
DVS
---
.. code-block:: python
'name': 'dvs1',
'max_mtu': 1000,
'uplink_names': [
'dvUplink1',
'dvUplink2',
'dvUplink3'
],
'capability': {
'portgroup_operation_supported': false,
'operation_supported': true,
'port_operation_supported': false
},
'lacp_api_version': 'multipleLag',
'contact_email': 'foo@email.com',
'product_info': {
'version':
'6.0.0',
'vendor':
'VMware,
Inc.',
'name':
'DVS'
},
'network_resource_management_enabled': true,
'contact_name': 'me@email.com',
'infrastructure_traffic_resource_pools': [
{
'reservation': 0,
'limit': 1000,
'share_level': 'high',
'key': 'management',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'faultTolerance',
'num_shares': 50
},
{
'reservation': 0,
'limit': 32000,
'share_level': 'normal',
'key': 'vmotion',
'num_shares': 50
},
{
'reservation': 10000,
'limit': -1,
'share_level': 'normal',
'key': 'virtualMachine',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'custom',
'key': 'iSCSI',
'num_shares': 75
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'nfs',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'hbr',
'num_shares': 50
},
{
'reservation': 8750,
'limit': 15000,
'share_level': 'high',
'key': 'vsan',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'vdp',
'num_shares': 50
}
],
'link_discovery_protocol': {
'operation':
'listen',
'protocol':
'cdp'
},
'network_resource_control_version': 'version3',
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attribute is: ``name``.
Portgroup
---------
.. code-block:: python
'security_policy': {
'allow_promiscuous': true,
'mac_changes': false,
'forged_transmits': true
},
'name': 'vmotion-v702',
'out_shaping': {
'enabled': true,
'average_bandwidth': 1500,
'burst_size': 4096,
'peak_bandwidth': 1500
},
'num_ports': 128,
'teaming': {
'port_order': {
'active': [
'dvUplink2'
],
'standby': [
'dvUplink1'
]
},
'notify_switches': false,
'reverse_policy': true,
'rolling_order': false,
'policy': 'failover_explicit',
'failure_criteria': {
'check_error_percent': true,
'full_duplex': false,
'check_duplex': false,
'percentage': 50,
'check_speed': 'minimum',
'speed': 20,
'check_beacon': true
}
},
'type': 'earlyBinding',
'vlan_id': 100,
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attributes are: ``name``, ``type``.
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.7.9,
or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original ESXi State
Module was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import sys
# Import Salt Libs
import salt.exceptions
from salt.ext import six
from salt.ext.six.moves import range
# Import Third Party Libs
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return 'dvs'
def mod_init(low):
'''
Init function
'''
return True
def _get_datacenter_name():
'''
Returns the datacenter name configured on the proxy
Supported proxies: esxcluster, esxdatacenter
'''
proxy_type = __salt__['vsphere.get_proxy_type']()
details = None
if proxy_type == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxy_type == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
if not details:
raise salt.exceptions.CommandExecutionError(
'details for proxy type \'{0}\' not loaded'.format(proxy_type))
return details['datacenter']
def dvs_configured(name, dvs):
'''
Configures a DVS.
Creates a new DVS, if it doesn't exist in the provided datacenter or
reconfigures it if configured differently.
dvs
DVS dict representations (see module sysdocs)
'''
datacenter_name = _get_datacenter_name()
dvs_name = dvs['name'] if dvs.get('name') else name
log.info('Running state %s for DVS \'%s\' in datacenter \'%s\'',
name, dvs_name, datacenter_name)
changes_required = False
ret = {'name': name, 'changes': {}, 'result': None, 'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO dvs validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
dvss = __salt__['vsphere.list_dvss'](dvs_names=[dvs_name],
service_instance=si)
if not dvss:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new DVS '
'\'{1}\' in datacenter \'{2}\''
''.format(name, dvs_name, datacenter_name))
log.info(comments[-1])
else:
dvs['name'] = dvs_name
__salt__['vsphere.create_dvs'](dvs_dict=dvs,
dvs_name=dvs_name,
service_instance=si)
comments.append('Created a new DVS \'{0}\' in datacenter '
'\'{1}\''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': dvs}})
else:
# DVS already exists. Checking various aspects of the config
props = ['description', 'contact_email', 'contact_name',
'lacp_api_version', 'link_discovery_protocol',
'max_mtu', 'network_resource_control_version',
'network_resource_management_enabled']
log.trace('DVS \'%s\' found in datacenter \'%s\'. Checking '
'for any updates in %s', dvs_name, datacenter_name, props)
props_to_original_values = {}
props_to_updated_values = {}
current_dvs = dvss[0]
for prop in props:
if prop in dvs and dvs[prop] != current_dvs.get(prop):
props_to_original_values[prop] = current_dvs.get(prop)
props_to_updated_values[prop] = dvs[prop]
# Simple infrastructure traffic resource control compare doesn't
# work because num_shares is optional if share_level is not custom
# We need to do a dedicated compare for this property
infra_prop = 'infrastructure_traffic_resource_pools'
original_infra_res_pools = []
updated_infra_res_pools = []
if infra_prop in dvs:
if not current_dvs.get(infra_prop):
updated_infra_res_pools = dvs[infra_prop]
else:
for idx in range(len(dvs[infra_prop])):
if 'num_shares' not in dvs[infra_prop][idx] and \
current_dvs[infra_prop][idx]['share_level'] != \
'custom' and \
'num_shares' in current_dvs[infra_prop][idx]:
del current_dvs[infra_prop][idx]['num_shares']
if dvs[infra_prop][idx] != \
current_dvs[infra_prop][idx]:
original_infra_res_pools.append(
current_dvs[infra_prop][idx])
updated_infra_res_pools.append(
dict(dvs[infra_prop][idx]))
if updated_infra_res_pools:
props_to_original_values[
'infrastructure_traffic_resource_pools'] = \
original_infra_res_pools
props_to_updated_values[
'infrastructure_traffic_resource_pools'] = \
updated_infra_res_pools
if props_to_updated_values:
if __opts__['test']:
changes_string = ''
for p in props_to_updated_values:
if p == 'infrastructure_traffic_resource_pools':
changes_string += \
'\tinfrastructure_traffic_resource_pools:\n'
for idx in range(len(props_to_updated_values[p])):
d = props_to_updated_values[p][idx]
s = props_to_original_values[p][idx]
changes_string += \
('\t\t{0} from \'{1}\' to \'{2}\'\n'
''.format(d['key'], s, d))
else:
changes_string += \
('\t{0} from \'{1}\' to \'{2}\'\n'
''.format(p, props_to_original_values[p],
props_to_updated_values[p]))
comments.append(
'State dvs_configured will update DVS \'{0}\' '
'in datacenter \'{1}\':\n{2}'
''.format(dvs_name, datacenter_name, changes_string))
log.info(comments[-1])
else:
__salt__['vsphere.update_dvs'](
dvs_dict=props_to_updated_values,
dvs=dvs_name,
service_instance=si)
comments.append('Updated DVS \'{0}\' in datacenter \'{1}\''
''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': props_to_updated_values,
'old': props_to_original_values}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': six.text_type(exc),
'result': False if not __opts__['test'] else None})
return ret
if not comments:
# We have no changes
ret.update({'comment': ('DVS \'{0}\' in datacenter \'{1}\' is '
'correctly configured. Nothing to be done.'
''.format(dvs_name, datacenter_name)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def _get_diff_dict(dict1, dict2):
'''
Returns a dictionary with the diffs between two dictionaries
It will ignore any key that doesn't exist in dict2
'''
ret_dict = {}
for p in dict2.keys():
if p not in dict1:
ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})
elif dict1[p] != dict2[p]:
if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):
sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])
if sub_diff_dict:
ret_dict.update({p: sub_diff_dict})
else:
ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})
return ret_dict
def _get_val2_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val2 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val2' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val2']})
else:
ret_dict.update(
{p: _get_val2_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_val1_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val1 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val1' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val1']})
else:
ret_dict.update(
{p: _get_val1_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def portgroups_configured(name, dvs, portgroups):
'''
Configures portgroups on a DVS.
Creates/updates/removes portgroups in a provided DVS
dvs
Name of the DVS
portgroups
Portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running state %s on DVS \'%s\', datacenter \'%s\'',
name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_pgs = __salt__['vsphere.list_dvportgroups'](
dvs=dvs, service_instance=si)
expected_pg_names = []
for pg in portgroups:
pg_name = pg['name']
expected_pg_names.append(pg_name)
del pg['name']
log.info('Checking pg \'%s\'', pg_name)
filtered_current_pgs = \
[p for p in current_pgs if p.get('name') == pg_name]
if not filtered_current_pgs:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new portgroup '
'\'{1}\' in DVS \'{2}\', datacenter '
'\'{3}\''.format(name, pg_name, dvs,
datacenter))
else:
__salt__['vsphere.create_dvportgroup'](
portgroup_dict=pg, portgroup_name=pg_name, dvs=dvs,
service_instance=si)
comments.append('Created a new portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update({pg_name: {'new': pg}})
else:
# Porgroup already exists. Checking the config
log.trace('Portgroup \'%s\' found in DVS \'%s\', datacenter '
'\'%s\'. Checking for any updates.',
pg_name, dvs, datacenter)
current_pg = filtered_current_pgs[0]
diff_dict = _get_diff_dict(current_pg, pg)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update portgroup \'{1}\' in '
'DVS \'{2}\', datacenter \'{3}\':\n{4}'
''.format(name, pg_name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=pg, portgroup=pg_name, dvs=dvs,
service_instance=si)
comments.append('Updated portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update(
{pg_name: {'new':
_get_val2_dict_from_diff_dict(diff_dict),
'old':
_get_val1_dict_from_diff_dict(diff_dict)}})
# Add the uplink portgroup to the expected pg names
uplink_pg = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
expected_pg_names.append(uplink_pg['name'])
# Remove any extra portgroups
for current_pg in current_pgs:
if current_pg['name'] not in expected_pg_names:
changes_required = True
if __opts__['test']:
comments.append('State {0} will remove '
'the portgroup \'{1}\' from DVS \'{2}\', '
'datacenter \'{3}\''
''.format(name, current_pg['name'], dvs,
datacenter))
else:
__salt__['vsphere.remove_dvportgroup'](
portgroup=current_pg['name'], dvs=dvs,
service_instance=si)
comments.append('Removed the portgroup \'{0}\' from DVS '
'\'{1}\', datacenter \'{2}\''
''.format(current_pg['name'], dvs,
datacenter))
log.info(comments[-1])
changes.update({current_pg['name']:
{'old': current_pg}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All portgroups in DVS \'{0}\', datacenter '
'\'{1}\' exist and are correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def uplink_portgroup_configured(name, dvs, uplink_portgroup):
'''
Configures the uplink portgroup on a DVS. The state assumes there is only
one uplink portgroup.
dvs
Name of the DVS
upling_portgroup
Uplink portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running %s on DVS \'%s\', datacenter \'%s\'', name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_uplink_portgroup = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
log.trace('current_uplink_portgroup = %s', current_uplink_portgroup)
diff_dict = _get_diff_dict(current_uplink_portgroup, uplink_portgroup)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update the '
'uplink portgroup in DVS \'{1}\', datacenter '
'\'{2}\':\n{3}'
''.format(name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=uplink_portgroup,
portgroup=current_uplink_portgroup['name'],
dvs=dvs,
service_instance=si)
comments.append('Updated the uplink portgroup in DVS '
'\'{0}\', datacenter \'{1}\''
''.format(dvs, datacenter))
log.info(comments[-1])
changes.update(
{'uplink_portgroup':
{'new': _get_val2_dict_from_diff_dict(diff_dict),
'old': _get_val1_dict_from_diff_dict(diff_dict)}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Uplink portgroup in DVS \'{0}\', datacenter '
'\'{1}\' is correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
saltstack/salt
|
salt/states/dvs.py
|
portgroups_configured
|
python
|
def portgroups_configured(name, dvs, portgroups):
'''
Configures portgroups on a DVS.
Creates/updates/removes portgroups in a provided DVS
dvs
Name of the DVS
portgroups
Portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running state %s on DVS \'%s\', datacenter \'%s\'',
name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_pgs = __salt__['vsphere.list_dvportgroups'](
dvs=dvs, service_instance=si)
expected_pg_names = []
for pg in portgroups:
pg_name = pg['name']
expected_pg_names.append(pg_name)
del pg['name']
log.info('Checking pg \'%s\'', pg_name)
filtered_current_pgs = \
[p for p in current_pgs if p.get('name') == pg_name]
if not filtered_current_pgs:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new portgroup '
'\'{1}\' in DVS \'{2}\', datacenter '
'\'{3}\''.format(name, pg_name, dvs,
datacenter))
else:
__salt__['vsphere.create_dvportgroup'](
portgroup_dict=pg, portgroup_name=pg_name, dvs=dvs,
service_instance=si)
comments.append('Created a new portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update({pg_name: {'new': pg}})
else:
# Porgroup already exists. Checking the config
log.trace('Portgroup \'%s\' found in DVS \'%s\', datacenter '
'\'%s\'. Checking for any updates.',
pg_name, dvs, datacenter)
current_pg = filtered_current_pgs[0]
diff_dict = _get_diff_dict(current_pg, pg)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update portgroup \'{1}\' in '
'DVS \'{2}\', datacenter \'{3}\':\n{4}'
''.format(name, pg_name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=pg, portgroup=pg_name, dvs=dvs,
service_instance=si)
comments.append('Updated portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update(
{pg_name: {'new':
_get_val2_dict_from_diff_dict(diff_dict),
'old':
_get_val1_dict_from_diff_dict(diff_dict)}})
# Add the uplink portgroup to the expected pg names
uplink_pg = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
expected_pg_names.append(uplink_pg['name'])
# Remove any extra portgroups
for current_pg in current_pgs:
if current_pg['name'] not in expected_pg_names:
changes_required = True
if __opts__['test']:
comments.append('State {0} will remove '
'the portgroup \'{1}\' from DVS \'{2}\', '
'datacenter \'{3}\''
''.format(name, current_pg['name'], dvs,
datacenter))
else:
__salt__['vsphere.remove_dvportgroup'](
portgroup=current_pg['name'], dvs=dvs,
service_instance=si)
comments.append('Removed the portgroup \'{0}\' from DVS '
'\'{1}\', datacenter \'{2}\''
''.format(current_pg['name'], dvs,
datacenter))
log.info(comments[-1])
changes.update({current_pg['name']:
{'old': current_pg}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All portgroups in DVS \'{0}\', datacenter '
'\'{1}\' exist and are correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
Configures portgroups on a DVS.
Creates/updates/removes portgroups in a provided DVS
dvs
Name of the DVS
portgroups
Portgroup dict representations (see module sysdocs)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dvs.py#L495-L628
|
[
"def _get_datacenter_name():\n '''\n Returns the datacenter name configured on the proxy\n\n Supported proxies: esxcluster, esxdatacenter\n '''\n\n proxy_type = __salt__['vsphere.get_proxy_type']()\n details = None\n if proxy_type == 'esxcluster':\n details = __salt__['esxcluster.get_details']()\n elif proxy_type == 'esxdatacenter':\n details = __salt__['esxdatacenter.get_details']()\n if not details:\n raise salt.exceptions.CommandExecutionError(\n 'details for proxy type \\'{0}\\' not loaded'.format(proxy_type))\n return details['datacenter']\n",
"def _get_diff_dict(dict1, dict2):\n '''\n Returns a dictionary with the diffs between two dictionaries\n\n It will ignore any key that doesn't exist in dict2\n '''\n ret_dict = {}\n for p in dict2.keys():\n if p not in dict1:\n ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})\n elif dict1[p] != dict2[p]:\n if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):\n sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])\n if sub_diff_dict:\n ret_dict.update({p: sub_diff_dict})\n else:\n ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})\n return ret_dict\n",
"def _get_val2_dict_from_diff_dict(diff_dict):\n '''\n Returns a dictionaries with the values stored in val2 of a diff dict.\n '''\n ret_dict = {}\n for p in diff_dict.keys():\n if not isinstance(diff_dict[p], dict):\n raise ValueError('Unexpected diff difct \\'{0}\\''.format(diff_dict))\n if 'val2' in diff_dict[p].keys():\n ret_dict.update({p: diff_dict[p]['val2']})\n else:\n ret_dict.update(\n {p: _get_val2_dict_from_diff_dict(diff_dict[p])})\n return ret_dict\n",
"def _get_val1_dict_from_diff_dict(diff_dict):\n '''\n Returns a dictionaries with the values stored in val1 of a diff dict.\n '''\n ret_dict = {}\n for p in diff_dict.keys():\n if not isinstance(diff_dict[p], dict):\n raise ValueError('Unexpected diff difct \\'{0}\\''.format(diff_dict))\n if 'val1' in diff_dict[p].keys():\n ret_dict.update({p: diff_dict[p]['val1']})\n else:\n ret_dict.update(\n {p: _get_val1_dict_from_diff_dict(diff_dict[p])})\n return ret_dict\n",
"def _get_changes_from_diff_dict(diff_dict):\n '''\n Returns a list of string message of the differences in a diff dict.\n\n Each inner message is tabulated one tab deeper\n '''\n changes_strings = []\n for p in diff_dict.keys():\n if not isinstance(diff_dict[p], dict):\n raise ValueError('Unexpected diff difct \\'{0}\\''.format(diff_dict))\n if sorted(diff_dict[p].keys()) == ['val1', 'val2']:\n # Some string formatting\n from_str = diff_dict[p]['val1']\n if isinstance(diff_dict[p]['val1'], six.string_types):\n from_str = '\\'{0}\\''.format(diff_dict[p]['val1'])\n elif isinstance(diff_dict[p]['val1'], list):\n from_str = '\\'{0}\\''.format(', '.join(diff_dict[p]['val1']))\n to_str = diff_dict[p]['val2']\n if isinstance(diff_dict[p]['val2'], six.string_types):\n to_str = '\\'{0}\\''.format(diff_dict[p]['val2'])\n elif isinstance(diff_dict[p]['val2'], list):\n to_str = '\\'{0}\\''.format(', '.join(diff_dict[p]['val2']))\n changes_strings.append('{0} from {1} to {2}'.format(\n p, from_str, to_str))\n else:\n sub_changes = _get_changes_from_diff_dict(diff_dict[p])\n if sub_changes:\n changes_strings.append('{0}:'.format(p))\n changes_strings.extend(['\\t{0}'.format(c)\n for c in sub_changes])\n return changes_strings\n"
] |
# -*- coding: utf-8 -*-
'''
Manage VMware distributed virtual switches (DVSs) and their distributed virtual
portgroups (DVportgroups).
:codeauthor: :email:`Alexandru Bleotu <alexandru.bleotu@morganstaley.com>`
Examples
========
Several settings can be changed for DVSs and DVporgroups. Here are two examples
covering all of the settings. Fewer settings can be used
DVS
---
.. code-block:: python
'name': 'dvs1',
'max_mtu': 1000,
'uplink_names': [
'dvUplink1',
'dvUplink2',
'dvUplink3'
],
'capability': {
'portgroup_operation_supported': false,
'operation_supported': true,
'port_operation_supported': false
},
'lacp_api_version': 'multipleLag',
'contact_email': 'foo@email.com',
'product_info': {
'version':
'6.0.0',
'vendor':
'VMware,
Inc.',
'name':
'DVS'
},
'network_resource_management_enabled': true,
'contact_name': 'me@email.com',
'infrastructure_traffic_resource_pools': [
{
'reservation': 0,
'limit': 1000,
'share_level': 'high',
'key': 'management',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'faultTolerance',
'num_shares': 50
},
{
'reservation': 0,
'limit': 32000,
'share_level': 'normal',
'key': 'vmotion',
'num_shares': 50
},
{
'reservation': 10000,
'limit': -1,
'share_level': 'normal',
'key': 'virtualMachine',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'custom',
'key': 'iSCSI',
'num_shares': 75
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'nfs',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'hbr',
'num_shares': 50
},
{
'reservation': 8750,
'limit': 15000,
'share_level': 'high',
'key': 'vsan',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'vdp',
'num_shares': 50
}
],
'link_discovery_protocol': {
'operation':
'listen',
'protocol':
'cdp'
},
'network_resource_control_version': 'version3',
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attribute is: ``name``.
Portgroup
---------
.. code-block:: python
'security_policy': {
'allow_promiscuous': true,
'mac_changes': false,
'forged_transmits': true
},
'name': 'vmotion-v702',
'out_shaping': {
'enabled': true,
'average_bandwidth': 1500,
'burst_size': 4096,
'peak_bandwidth': 1500
},
'num_ports': 128,
'teaming': {
'port_order': {
'active': [
'dvUplink2'
],
'standby': [
'dvUplink1'
]
},
'notify_switches': false,
'reverse_policy': true,
'rolling_order': false,
'policy': 'failover_explicit',
'failure_criteria': {
'check_error_percent': true,
'full_duplex': false,
'check_duplex': false,
'percentage': 50,
'check_speed': 'minimum',
'speed': 20,
'check_beacon': true
}
},
'type': 'earlyBinding',
'vlan_id': 100,
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attributes are: ``name``, ``type``.
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.7.9,
or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original ESXi State
Module was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import sys
# Import Salt Libs
import salt.exceptions
from salt.ext import six
from salt.ext.six.moves import range
# Import Third Party Libs
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return 'dvs'
def mod_init(low):
'''
Init function
'''
return True
def _get_datacenter_name():
'''
Returns the datacenter name configured on the proxy
Supported proxies: esxcluster, esxdatacenter
'''
proxy_type = __salt__['vsphere.get_proxy_type']()
details = None
if proxy_type == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxy_type == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
if not details:
raise salt.exceptions.CommandExecutionError(
'details for proxy type \'{0}\' not loaded'.format(proxy_type))
return details['datacenter']
def dvs_configured(name, dvs):
'''
Configures a DVS.
Creates a new DVS, if it doesn't exist in the provided datacenter or
reconfigures it if configured differently.
dvs
DVS dict representations (see module sysdocs)
'''
datacenter_name = _get_datacenter_name()
dvs_name = dvs['name'] if dvs.get('name') else name
log.info('Running state %s for DVS \'%s\' in datacenter \'%s\'',
name, dvs_name, datacenter_name)
changes_required = False
ret = {'name': name, 'changes': {}, 'result': None, 'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO dvs validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
dvss = __salt__['vsphere.list_dvss'](dvs_names=[dvs_name],
service_instance=si)
if not dvss:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new DVS '
'\'{1}\' in datacenter \'{2}\''
''.format(name, dvs_name, datacenter_name))
log.info(comments[-1])
else:
dvs['name'] = dvs_name
__salt__['vsphere.create_dvs'](dvs_dict=dvs,
dvs_name=dvs_name,
service_instance=si)
comments.append('Created a new DVS \'{0}\' in datacenter '
'\'{1}\''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': dvs}})
else:
# DVS already exists. Checking various aspects of the config
props = ['description', 'contact_email', 'contact_name',
'lacp_api_version', 'link_discovery_protocol',
'max_mtu', 'network_resource_control_version',
'network_resource_management_enabled']
log.trace('DVS \'%s\' found in datacenter \'%s\'. Checking '
'for any updates in %s', dvs_name, datacenter_name, props)
props_to_original_values = {}
props_to_updated_values = {}
current_dvs = dvss[0]
for prop in props:
if prop in dvs and dvs[prop] != current_dvs.get(prop):
props_to_original_values[prop] = current_dvs.get(prop)
props_to_updated_values[prop] = dvs[prop]
# Simple infrastructure traffic resource control compare doesn't
# work because num_shares is optional if share_level is not custom
# We need to do a dedicated compare for this property
infra_prop = 'infrastructure_traffic_resource_pools'
original_infra_res_pools = []
updated_infra_res_pools = []
if infra_prop in dvs:
if not current_dvs.get(infra_prop):
updated_infra_res_pools = dvs[infra_prop]
else:
for idx in range(len(dvs[infra_prop])):
if 'num_shares' not in dvs[infra_prop][idx] and \
current_dvs[infra_prop][idx]['share_level'] != \
'custom' and \
'num_shares' in current_dvs[infra_prop][idx]:
del current_dvs[infra_prop][idx]['num_shares']
if dvs[infra_prop][idx] != \
current_dvs[infra_prop][idx]:
original_infra_res_pools.append(
current_dvs[infra_prop][idx])
updated_infra_res_pools.append(
dict(dvs[infra_prop][idx]))
if updated_infra_res_pools:
props_to_original_values[
'infrastructure_traffic_resource_pools'] = \
original_infra_res_pools
props_to_updated_values[
'infrastructure_traffic_resource_pools'] = \
updated_infra_res_pools
if props_to_updated_values:
if __opts__['test']:
changes_string = ''
for p in props_to_updated_values:
if p == 'infrastructure_traffic_resource_pools':
changes_string += \
'\tinfrastructure_traffic_resource_pools:\n'
for idx in range(len(props_to_updated_values[p])):
d = props_to_updated_values[p][idx]
s = props_to_original_values[p][idx]
changes_string += \
('\t\t{0} from \'{1}\' to \'{2}\'\n'
''.format(d['key'], s, d))
else:
changes_string += \
('\t{0} from \'{1}\' to \'{2}\'\n'
''.format(p, props_to_original_values[p],
props_to_updated_values[p]))
comments.append(
'State dvs_configured will update DVS \'{0}\' '
'in datacenter \'{1}\':\n{2}'
''.format(dvs_name, datacenter_name, changes_string))
log.info(comments[-1])
else:
__salt__['vsphere.update_dvs'](
dvs_dict=props_to_updated_values,
dvs=dvs_name,
service_instance=si)
comments.append('Updated DVS \'{0}\' in datacenter \'{1}\''
''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': props_to_updated_values,
'old': props_to_original_values}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': six.text_type(exc),
'result': False if not __opts__['test'] else None})
return ret
if not comments:
# We have no changes
ret.update({'comment': ('DVS \'{0}\' in datacenter \'{1}\' is '
'correctly configured. Nothing to be done.'
''.format(dvs_name, datacenter_name)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def _get_diff_dict(dict1, dict2):
'''
Returns a dictionary with the diffs between two dictionaries
It will ignore any key that doesn't exist in dict2
'''
ret_dict = {}
for p in dict2.keys():
if p not in dict1:
ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})
elif dict1[p] != dict2[p]:
if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):
sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])
if sub_diff_dict:
ret_dict.update({p: sub_diff_dict})
else:
ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})
return ret_dict
def _get_val2_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val2 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val2' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val2']})
else:
ret_dict.update(
{p: _get_val2_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_val1_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val1 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val1' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val1']})
else:
ret_dict.update(
{p: _get_val1_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_changes_from_diff_dict(diff_dict):
'''
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
'''
changes_strings = []
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if sorted(diff_dict[p].keys()) == ['val1', 'val2']:
# Some string formatting
from_str = diff_dict[p]['val1']
if isinstance(diff_dict[p]['val1'], six.string_types):
from_str = '\'{0}\''.format(diff_dict[p]['val1'])
elif isinstance(diff_dict[p]['val1'], list):
from_str = '\'{0}\''.format(', '.join(diff_dict[p]['val1']))
to_str = diff_dict[p]['val2']
if isinstance(diff_dict[p]['val2'], six.string_types):
to_str = '\'{0}\''.format(diff_dict[p]['val2'])
elif isinstance(diff_dict[p]['val2'], list):
to_str = '\'{0}\''.format(', '.join(diff_dict[p]['val2']))
changes_strings.append('{0} from {1} to {2}'.format(
p, from_str, to_str))
else:
sub_changes = _get_changes_from_diff_dict(diff_dict[p])
if sub_changes:
changes_strings.append('{0}:'.format(p))
changes_strings.extend(['\t{0}'.format(c)
for c in sub_changes])
return changes_strings
def uplink_portgroup_configured(name, dvs, uplink_portgroup):
'''
Configures the uplink portgroup on a DVS. The state assumes there is only
one uplink portgroup.
dvs
Name of the DVS
upling_portgroup
Uplink portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running %s on DVS \'%s\', datacenter \'%s\'', name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_uplink_portgroup = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
log.trace('current_uplink_portgroup = %s', current_uplink_portgroup)
diff_dict = _get_diff_dict(current_uplink_portgroup, uplink_portgroup)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update the '
'uplink portgroup in DVS \'{1}\', datacenter '
'\'{2}\':\n{3}'
''.format(name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=uplink_portgroup,
portgroup=current_uplink_portgroup['name'],
dvs=dvs,
service_instance=si)
comments.append('Updated the uplink portgroup in DVS '
'\'{0}\', datacenter \'{1}\''
''.format(dvs, datacenter))
log.info(comments[-1])
changes.update(
{'uplink_portgroup':
{'new': _get_val2_dict_from_diff_dict(diff_dict),
'old': _get_val1_dict_from_diff_dict(diff_dict)}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Uplink portgroup in DVS \'{0}\', datacenter '
'\'{1}\' is correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
saltstack/salt
|
salt/states/dvs.py
|
uplink_portgroup_configured
|
python
|
def uplink_portgroup_configured(name, dvs, uplink_portgroup):
'''
Configures the uplink portgroup on a DVS. The state assumes there is only
one uplink portgroup.
dvs
Name of the DVS
upling_portgroup
Uplink portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running %s on DVS \'%s\', datacenter \'%s\'', name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_uplink_portgroup = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
log.trace('current_uplink_portgroup = %s', current_uplink_portgroup)
diff_dict = _get_diff_dict(current_uplink_portgroup, uplink_portgroup)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update the '
'uplink portgroup in DVS \'{1}\', datacenter '
'\'{2}\':\n{3}'
''.format(name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=uplink_portgroup,
portgroup=current_uplink_portgroup['name'],
dvs=dvs,
service_instance=si)
comments.append('Updated the uplink portgroup in DVS '
'\'{0}\', datacenter \'{1}\''
''.format(dvs, datacenter))
log.info(comments[-1])
changes.update(
{'uplink_portgroup':
{'new': _get_val2_dict_from_diff_dict(diff_dict),
'old': _get_val1_dict_from_diff_dict(diff_dict)}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Uplink portgroup in DVS \'{0}\', datacenter '
'\'{1}\' is correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
Configures the uplink portgroup on a DVS. The state assumes there is only
one uplink portgroup.
dvs
Name of the DVS
upling_portgroup
Uplink portgroup dict representations (see module sysdocs)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dvs.py#L631-L710
|
[
"def _get_datacenter_name():\n '''\n Returns the datacenter name configured on the proxy\n\n Supported proxies: esxcluster, esxdatacenter\n '''\n\n proxy_type = __salt__['vsphere.get_proxy_type']()\n details = None\n if proxy_type == 'esxcluster':\n details = __salt__['esxcluster.get_details']()\n elif proxy_type == 'esxdatacenter':\n details = __salt__['esxdatacenter.get_details']()\n if not details:\n raise salt.exceptions.CommandExecutionError(\n 'details for proxy type \\'{0}\\' not loaded'.format(proxy_type))\n return details['datacenter']\n",
"def _get_diff_dict(dict1, dict2):\n '''\n Returns a dictionary with the diffs between two dictionaries\n\n It will ignore any key that doesn't exist in dict2\n '''\n ret_dict = {}\n for p in dict2.keys():\n if p not in dict1:\n ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})\n elif dict1[p] != dict2[p]:\n if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):\n sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])\n if sub_diff_dict:\n ret_dict.update({p: sub_diff_dict})\n else:\n ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})\n return ret_dict\n",
"def _get_val2_dict_from_diff_dict(diff_dict):\n '''\n Returns a dictionaries with the values stored in val2 of a diff dict.\n '''\n ret_dict = {}\n for p in diff_dict.keys():\n if not isinstance(diff_dict[p], dict):\n raise ValueError('Unexpected diff difct \\'{0}\\''.format(diff_dict))\n if 'val2' in diff_dict[p].keys():\n ret_dict.update({p: diff_dict[p]['val2']})\n else:\n ret_dict.update(\n {p: _get_val2_dict_from_diff_dict(diff_dict[p])})\n return ret_dict\n",
"def _get_val1_dict_from_diff_dict(diff_dict):\n '''\n Returns a dictionaries with the values stored in val1 of a diff dict.\n '''\n ret_dict = {}\n for p in diff_dict.keys():\n if not isinstance(diff_dict[p], dict):\n raise ValueError('Unexpected diff difct \\'{0}\\''.format(diff_dict))\n if 'val1' in diff_dict[p].keys():\n ret_dict.update({p: diff_dict[p]['val1']})\n else:\n ret_dict.update(\n {p: _get_val1_dict_from_diff_dict(diff_dict[p])})\n return ret_dict\n",
"def _get_changes_from_diff_dict(diff_dict):\n '''\n Returns a list of string message of the differences in a diff dict.\n\n Each inner message is tabulated one tab deeper\n '''\n changes_strings = []\n for p in diff_dict.keys():\n if not isinstance(diff_dict[p], dict):\n raise ValueError('Unexpected diff difct \\'{0}\\''.format(diff_dict))\n if sorted(diff_dict[p].keys()) == ['val1', 'val2']:\n # Some string formatting\n from_str = diff_dict[p]['val1']\n if isinstance(diff_dict[p]['val1'], six.string_types):\n from_str = '\\'{0}\\''.format(diff_dict[p]['val1'])\n elif isinstance(diff_dict[p]['val1'], list):\n from_str = '\\'{0}\\''.format(', '.join(diff_dict[p]['val1']))\n to_str = diff_dict[p]['val2']\n if isinstance(diff_dict[p]['val2'], six.string_types):\n to_str = '\\'{0}\\''.format(diff_dict[p]['val2'])\n elif isinstance(diff_dict[p]['val2'], list):\n to_str = '\\'{0}\\''.format(', '.join(diff_dict[p]['val2']))\n changes_strings.append('{0} from {1} to {2}'.format(\n p, from_str, to_str))\n else:\n sub_changes = _get_changes_from_diff_dict(diff_dict[p])\n if sub_changes:\n changes_strings.append('{0}:'.format(p))\n changes_strings.extend(['\\t{0}'.format(c)\n for c in sub_changes])\n return changes_strings\n"
] |
# -*- coding: utf-8 -*-
'''
Manage VMware distributed virtual switches (DVSs) and their distributed virtual
portgroups (DVportgroups).
:codeauthor: :email:`Alexandru Bleotu <alexandru.bleotu@morganstaley.com>`
Examples
========
Several settings can be changed for DVSs and DVporgroups. Here are two examples
covering all of the settings. Fewer settings can be used
DVS
---
.. code-block:: python
'name': 'dvs1',
'max_mtu': 1000,
'uplink_names': [
'dvUplink1',
'dvUplink2',
'dvUplink3'
],
'capability': {
'portgroup_operation_supported': false,
'operation_supported': true,
'port_operation_supported': false
},
'lacp_api_version': 'multipleLag',
'contact_email': 'foo@email.com',
'product_info': {
'version':
'6.0.0',
'vendor':
'VMware,
Inc.',
'name':
'DVS'
},
'network_resource_management_enabled': true,
'contact_name': 'me@email.com',
'infrastructure_traffic_resource_pools': [
{
'reservation': 0,
'limit': 1000,
'share_level': 'high',
'key': 'management',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'faultTolerance',
'num_shares': 50
},
{
'reservation': 0,
'limit': 32000,
'share_level': 'normal',
'key': 'vmotion',
'num_shares': 50
},
{
'reservation': 10000,
'limit': -1,
'share_level': 'normal',
'key': 'virtualMachine',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'custom',
'key': 'iSCSI',
'num_shares': 75
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'nfs',
'num_shares': 50
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'hbr',
'num_shares': 50
},
{
'reservation': 8750,
'limit': 15000,
'share_level': 'high',
'key': 'vsan',
'num_shares': 100
},
{
'reservation': 0,
'limit': -1,
'share_level': 'normal',
'key': 'vdp',
'num_shares': 50
}
],
'link_discovery_protocol': {
'operation':
'listen',
'protocol':
'cdp'
},
'network_resource_control_version': 'version3',
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attribute is: ``name``.
Portgroup
---------
.. code-block:: python
'security_policy': {
'allow_promiscuous': true,
'mac_changes': false,
'forged_transmits': true
},
'name': 'vmotion-v702',
'out_shaping': {
'enabled': true,
'average_bandwidth': 1500,
'burst_size': 4096,
'peak_bandwidth': 1500
},
'num_ports': 128,
'teaming': {
'port_order': {
'active': [
'dvUplink2'
],
'standby': [
'dvUplink1'
]
},
'notify_switches': false,
'reverse_policy': true,
'rolling_order': false,
'policy': 'failover_explicit',
'failure_criteria': {
'check_error_percent': true,
'full_duplex': false,
'check_duplex': false,
'percentage': 50,
'check_speed': 'minimum',
'speed': 20,
'check_beacon': true
}
},
'type': 'earlyBinding',
'vlan_id': 100,
'description': 'Managed by Salt. Random settings.'
Note: The mandatory attributes are: ``name``, ``type``.
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.7.9,
or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original ESXi State
Module was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import sys
# Import Salt Libs
import salt.exceptions
from salt.ext import six
from salt.ext.six.moves import range
# Import Third Party Libs
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return 'dvs'
def mod_init(low):
'''
Init function
'''
return True
def _get_datacenter_name():
'''
Returns the datacenter name configured on the proxy
Supported proxies: esxcluster, esxdatacenter
'''
proxy_type = __salt__['vsphere.get_proxy_type']()
details = None
if proxy_type == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxy_type == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
if not details:
raise salt.exceptions.CommandExecutionError(
'details for proxy type \'{0}\' not loaded'.format(proxy_type))
return details['datacenter']
def dvs_configured(name, dvs):
'''
Configures a DVS.
Creates a new DVS, if it doesn't exist in the provided datacenter or
reconfigures it if configured differently.
dvs
DVS dict representations (see module sysdocs)
'''
datacenter_name = _get_datacenter_name()
dvs_name = dvs['name'] if dvs.get('name') else name
log.info('Running state %s for DVS \'%s\' in datacenter \'%s\'',
name, dvs_name, datacenter_name)
changes_required = False
ret = {'name': name, 'changes': {}, 'result': None, 'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO dvs validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
dvss = __salt__['vsphere.list_dvss'](dvs_names=[dvs_name],
service_instance=si)
if not dvss:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new DVS '
'\'{1}\' in datacenter \'{2}\''
''.format(name, dvs_name, datacenter_name))
log.info(comments[-1])
else:
dvs['name'] = dvs_name
__salt__['vsphere.create_dvs'](dvs_dict=dvs,
dvs_name=dvs_name,
service_instance=si)
comments.append('Created a new DVS \'{0}\' in datacenter '
'\'{1}\''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': dvs}})
else:
# DVS already exists. Checking various aspects of the config
props = ['description', 'contact_email', 'contact_name',
'lacp_api_version', 'link_discovery_protocol',
'max_mtu', 'network_resource_control_version',
'network_resource_management_enabled']
log.trace('DVS \'%s\' found in datacenter \'%s\'. Checking '
'for any updates in %s', dvs_name, datacenter_name, props)
props_to_original_values = {}
props_to_updated_values = {}
current_dvs = dvss[0]
for prop in props:
if prop in dvs and dvs[prop] != current_dvs.get(prop):
props_to_original_values[prop] = current_dvs.get(prop)
props_to_updated_values[prop] = dvs[prop]
# Simple infrastructure traffic resource control compare doesn't
# work because num_shares is optional if share_level is not custom
# We need to do a dedicated compare for this property
infra_prop = 'infrastructure_traffic_resource_pools'
original_infra_res_pools = []
updated_infra_res_pools = []
if infra_prop in dvs:
if not current_dvs.get(infra_prop):
updated_infra_res_pools = dvs[infra_prop]
else:
for idx in range(len(dvs[infra_prop])):
if 'num_shares' not in dvs[infra_prop][idx] and \
current_dvs[infra_prop][idx]['share_level'] != \
'custom' and \
'num_shares' in current_dvs[infra_prop][idx]:
del current_dvs[infra_prop][idx]['num_shares']
if dvs[infra_prop][idx] != \
current_dvs[infra_prop][idx]:
original_infra_res_pools.append(
current_dvs[infra_prop][idx])
updated_infra_res_pools.append(
dict(dvs[infra_prop][idx]))
if updated_infra_res_pools:
props_to_original_values[
'infrastructure_traffic_resource_pools'] = \
original_infra_res_pools
props_to_updated_values[
'infrastructure_traffic_resource_pools'] = \
updated_infra_res_pools
if props_to_updated_values:
if __opts__['test']:
changes_string = ''
for p in props_to_updated_values:
if p == 'infrastructure_traffic_resource_pools':
changes_string += \
'\tinfrastructure_traffic_resource_pools:\n'
for idx in range(len(props_to_updated_values[p])):
d = props_to_updated_values[p][idx]
s = props_to_original_values[p][idx]
changes_string += \
('\t\t{0} from \'{1}\' to \'{2}\'\n'
''.format(d['key'], s, d))
else:
changes_string += \
('\t{0} from \'{1}\' to \'{2}\'\n'
''.format(p, props_to_original_values[p],
props_to_updated_values[p]))
comments.append(
'State dvs_configured will update DVS \'{0}\' '
'in datacenter \'{1}\':\n{2}'
''.format(dvs_name, datacenter_name, changes_string))
log.info(comments[-1])
else:
__salt__['vsphere.update_dvs'](
dvs_dict=props_to_updated_values,
dvs=dvs_name,
service_instance=si)
comments.append('Updated DVS \'{0}\' in datacenter \'{1}\''
''.format(dvs_name, datacenter_name))
log.info(comments[-1])
changes.update({'dvs': {'new': props_to_updated_values,
'old': props_to_original_values}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': six.text_type(exc),
'result': False if not __opts__['test'] else None})
return ret
if not comments:
# We have no changes
ret.update({'comment': ('DVS \'{0}\' in datacenter \'{1}\' is '
'correctly configured. Nothing to be done.'
''.format(dvs_name, datacenter_name)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def _get_diff_dict(dict1, dict2):
'''
Returns a dictionary with the diffs between two dictionaries
It will ignore any key that doesn't exist in dict2
'''
ret_dict = {}
for p in dict2.keys():
if p not in dict1:
ret_dict.update({p: {'val1': None, 'val2': dict2[p]}})
elif dict1[p] != dict2[p]:
if isinstance(dict1[p], dict) and isinstance(dict2[p], dict):
sub_diff_dict = _get_diff_dict(dict1[p], dict2[p])
if sub_diff_dict:
ret_dict.update({p: sub_diff_dict})
else:
ret_dict.update({p: {'val1': dict1[p], 'val2': dict2[p]}})
return ret_dict
def _get_val2_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val2 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val2' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val2']})
else:
ret_dict.update(
{p: _get_val2_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_val1_dict_from_diff_dict(diff_dict):
'''
Returns a dictionaries with the values stored in val1 of a diff dict.
'''
ret_dict = {}
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if 'val1' in diff_dict[p].keys():
ret_dict.update({p: diff_dict[p]['val1']})
else:
ret_dict.update(
{p: _get_val1_dict_from_diff_dict(diff_dict[p])})
return ret_dict
def _get_changes_from_diff_dict(diff_dict):
'''
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
'''
changes_strings = []
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Unexpected diff difct \'{0}\''.format(diff_dict))
if sorted(diff_dict[p].keys()) == ['val1', 'val2']:
# Some string formatting
from_str = diff_dict[p]['val1']
if isinstance(diff_dict[p]['val1'], six.string_types):
from_str = '\'{0}\''.format(diff_dict[p]['val1'])
elif isinstance(diff_dict[p]['val1'], list):
from_str = '\'{0}\''.format(', '.join(diff_dict[p]['val1']))
to_str = diff_dict[p]['val2']
if isinstance(diff_dict[p]['val2'], six.string_types):
to_str = '\'{0}\''.format(diff_dict[p]['val2'])
elif isinstance(diff_dict[p]['val2'], list):
to_str = '\'{0}\''.format(', '.join(diff_dict[p]['val2']))
changes_strings.append('{0} from {1} to {2}'.format(
p, from_str, to_str))
else:
sub_changes = _get_changes_from_diff_dict(diff_dict[p])
if sub_changes:
changes_strings.append('{0}:'.format(p))
changes_strings.extend(['\t{0}'.format(c)
for c in sub_changes])
return changes_strings
def portgroups_configured(name, dvs, portgroups):
'''
Configures portgroups on a DVS.
Creates/updates/removes portgroups in a provided DVS
dvs
Name of the DVS
portgroups
Portgroup dict representations (see module sysdocs)
'''
datacenter = _get_datacenter_name()
log.info('Running state %s on DVS \'%s\', datacenter \'%s\'',
name, dvs, datacenter)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
try:
#TODO portroups validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_pgs = __salt__['vsphere.list_dvportgroups'](
dvs=dvs, service_instance=si)
expected_pg_names = []
for pg in portgroups:
pg_name = pg['name']
expected_pg_names.append(pg_name)
del pg['name']
log.info('Checking pg \'%s\'', pg_name)
filtered_current_pgs = \
[p for p in current_pgs if p.get('name') == pg_name]
if not filtered_current_pgs:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create a new portgroup '
'\'{1}\' in DVS \'{2}\', datacenter '
'\'{3}\''.format(name, pg_name, dvs,
datacenter))
else:
__salt__['vsphere.create_dvportgroup'](
portgroup_dict=pg, portgroup_name=pg_name, dvs=dvs,
service_instance=si)
comments.append('Created a new portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update({pg_name: {'new': pg}})
else:
# Porgroup already exists. Checking the config
log.trace('Portgroup \'%s\' found in DVS \'%s\', datacenter '
'\'%s\'. Checking for any updates.',
pg_name, dvs, datacenter)
current_pg = filtered_current_pgs[0]
diff_dict = _get_diff_dict(current_pg, pg)
if diff_dict:
changes_required = True
if __opts__['test']:
changes_strings = \
_get_changes_from_diff_dict(diff_dict)
log.trace('changes_strings = %s', changes_strings)
comments.append(
'State {0} will update portgroup \'{1}\' in '
'DVS \'{2}\', datacenter \'{3}\':\n{4}'
''.format(name, pg_name, dvs, datacenter,
'\n'.join(['\t{0}'.format(c) for c in
changes_strings])))
else:
__salt__['vsphere.update_dvportgroup'](
portgroup_dict=pg, portgroup=pg_name, dvs=dvs,
service_instance=si)
comments.append('Updated portgroup \'{0}\' in DVS '
'\'{1}\', datacenter \'{2}\''
''.format(pg_name, dvs, datacenter))
log.info(comments[-1])
changes.update(
{pg_name: {'new':
_get_val2_dict_from_diff_dict(diff_dict),
'old':
_get_val1_dict_from_diff_dict(diff_dict)}})
# Add the uplink portgroup to the expected pg names
uplink_pg = __salt__['vsphere.list_uplink_dvportgroup'](
dvs=dvs, service_instance=si)
expected_pg_names.append(uplink_pg['name'])
# Remove any extra portgroups
for current_pg in current_pgs:
if current_pg['name'] not in expected_pg_names:
changes_required = True
if __opts__['test']:
comments.append('State {0} will remove '
'the portgroup \'{1}\' from DVS \'{2}\', '
'datacenter \'{3}\''
''.format(name, current_pg['name'], dvs,
datacenter))
else:
__salt__['vsphere.remove_dvportgroup'](
portgroup=current_pg['name'], dvs=dvs,
service_instance=si)
comments.append('Removed the portgroup \'{0}\' from DVS '
'\'{1}\', datacenter \'{2}\''
''.format(current_pg['name'], dvs,
datacenter))
log.info(comments[-1])
changes.update({current_pg['name']:
{'old': current_pg}})
__salt__['vsphere.disconnect'](si)
except salt.exceptions.CommandExecutionError as exc:
log.exception('Encountered error')
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All portgroups in DVS \'{0}\', datacenter '
'\'{1}\' exist and are correctly configured. '
'Nothing to be done.'.format(dvs, datacenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
saltstack/salt
|
salt/states/postgres_user.py
|
present
|
python
|
def present(name,
createdb=None,
createroles=None,
encrypted=None,
superuser=None,
replication=None,
inherit=None,
login=None,
password=None,
default_password=None,
refresh_password=None,
valid_until=None,
groups=None,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named user is present with the specified privileges
Please note that the user/group notion in postgresql is just abstract, we
have roles, where users can be seens as roles with the LOGIN privilege
and groups the others.
name
The name of the system user to manage.
createdb
Is the user allowed to create databases?
createroles
Is the user allowed to create other users?
encrypted
Should the password be encrypted in the system catalog?
login
Should the group have login perm
inherit
Should the group inherit permissions
superuser
Should the new user be a "superuser"
replication
Should the new user be allowed to initiate streaming replication
password
The system user's password. It can be either a plain string or a
md5 postgresql hashed password::
'md5{MD5OF({password}{role}}'
If encrypted is None or True, the password will be automatically
encrypted to the previous
format if it is not already done.
default_password
The password used only when creating the user, unless password is set.
.. versionadded:: 2016.3.0
refresh_password
Password refresh flag
Boolean attribute to specify whether to password comparison check
should be performed.
If refresh_password is ``True``, the password will be automatically
updated without extra password change check.
This behaviour makes it possible to execute in environments without
superuser access available, e.g. Amazon RDS for PostgreSQL
valid_until
A date and time after which the role's password is no longer valid.
groups
A string of comma separated groups the user should be in
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
db_user
Postgres database username, if different from config or default.
db_password
Postgres user's password, if any password, for a specified db_user.
db_host
Postgres database host, if different from config or default.
db_port
Postgres database port, if different from config or default.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User {0} is already present'.format(name)}
# default to encrypted passwords
if encrypted is not False:
encrypted = postgres._DEFAULT_PASSWORDS_ENCRYPTION
# maybe encrypt if it's not already and necessary
password = postgres._maybe_encrypt_password(name,
password,
encrypted=encrypted)
if default_password is not None:
default_password = postgres._maybe_encrypt_password(name,
default_password,
encrypted=encrypted)
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
# check if user exists
mode = 'create'
user_attr = __salt__['postgres.role_get'](
name, return_password=not refresh_password, **db_args)
if user_attr is not None:
mode = 'update'
cret = None
update = {}
if mode == 'update':
user_groups = user_attr.get('groups', [])
if (
createdb is not None
and user_attr['can create databases'] != createdb
):
update['createdb'] = createdb
if (
inherit is not None
and user_attr['inherits privileges'] != inherit
):
update['inherit'] = inherit
if login is not None and user_attr['can login'] != login:
update['login'] = login
if (
createroles is not None
and user_attr['can create roles'] != createroles
):
update['createroles'] = createroles
if (
replication is not None
and user_attr['replication'] != replication
):
update['replication'] = replication
if superuser is not None and user_attr['superuser'] != superuser:
update['superuser'] = superuser
if password is not None and (refresh_password or user_attr['password'] != password):
update['password'] = True
if valid_until is not None:
valid_until_dt = __salt__['postgres.psql_query'](
'SELECT \'{0}\'::timestamp(0) as dt;'.format(
valid_until.replace('\'', '\'\'')),
**db_args)[0]['dt']
try:
valid_until_dt = datetime.datetime.strptime(
valid_until_dt, '%Y-%m-%d %H:%M:%S')
except ValueError:
valid_until_dt = None
if valid_until_dt != user_attr['expiry time']:
update['valid_until'] = valid_until
if groups is not None:
lgroups = groups
if isinstance(groups, (six.string_types, six.text_type)):
lgroups = lgroups.split(',')
if isinstance(lgroups, list):
missing_groups = [a for a in lgroups if a not in user_groups]
if missing_groups:
update['groups'] = missing_groups
if mode == 'create' and password is None:
password = default_password
if mode == 'create' or (mode == 'update' and update):
if __opts__['test']:
if update:
ret['changes'][name] = update
ret['result'] = None
ret['comment'] = 'User {0} is set to be {1}d'.format(name, mode)
return ret
cret = __salt__['postgres.user_{0}'.format(mode)](
username=name,
createdb=createdb,
createroles=createroles,
encrypted=encrypted,
superuser=superuser,
login=login,
inherit=inherit,
replication=replication,
rolepassword=password,
valid_until=valid_until,
groups=groups,
**db_args)
else:
cret = None
if cret:
ret['comment'] = 'The user {0} has been {1}d'.format(name, mode)
if update:
ret['changes'][name] = update
else:
ret['changes'][name] = 'Present'
elif cret is not None:
ret['comment'] = 'Failed to create user {0}'.format(name)
ret['result'] = False
else:
ret['result'] = True
return ret
|
Ensure that the named user is present with the specified privileges
Please note that the user/group notion in postgresql is just abstract, we
have roles, where users can be seens as roles with the LOGIN privilege
and groups the others.
name
The name of the system user to manage.
createdb
Is the user allowed to create databases?
createroles
Is the user allowed to create other users?
encrypted
Should the password be encrypted in the system catalog?
login
Should the group have login perm
inherit
Should the group inherit permissions
superuser
Should the new user be a "superuser"
replication
Should the new user be allowed to initiate streaming replication
password
The system user's password. It can be either a plain string or a
md5 postgresql hashed password::
'md5{MD5OF({password}{role}}'
If encrypted is None or True, the password will be automatically
encrypted to the previous
format if it is not already done.
default_password
The password used only when creating the user, unless password is set.
.. versionadded:: 2016.3.0
refresh_password
Password refresh flag
Boolean attribute to specify whether to password comparison check
should be performed.
If refresh_password is ``True``, the password will be automatically
updated without extra password change check.
This behaviour makes it possible to execute in environments without
superuser access available, e.g. Amazon RDS for PostgreSQL
valid_until
A date and time after which the role's password is no longer valid.
groups
A string of comma separated groups the user should be in
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
db_user
Postgres database username, if different from config or default.
db_password
Postgres user's password, if any password, for a specified db_user.
db_host
Postgres database host, if different from config or default.
db_port
Postgres database port, if different from config or default.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_user.py#L37-L259
|
[
"def _maybe_encrypt_password(role,\n password,\n encrypted=_DEFAULT_PASSWORDS_ENCRYPTION):\n '''\n pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}'\n '''\n if password is not None:\n password = six.text_type(password)\n if encrypted and password and not password.startswith('md5'):\n password = \"md5{0}\".format(\n hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest())\n return password\n"
] |
# -*- coding: utf-8 -*-
'''
Management of PostgreSQL users (roles)
======================================
The postgres_users module is used to create and manage Postgres users.
.. code-block:: yaml
frank:
postgres_user.present
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
import datetime
import logging
# Import salt libs
# Salt imports
from salt.modules import postgres
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if the postgres module is present
'''
if 'postgres.user_exists' not in __salt__:
return (False, 'Unable to load postgres module. Make sure `postgres.bins_dir` is set.')
return True
def absent(name,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named user is absent
name
The username of the user to remove
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
db_user
database username if different from config or default
db_password
user password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
# check if user exists and remove it
if __salt__['postgres.user_exists'](name, **db_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} is set to be removed'.format(name)
return ret
if __salt__['postgres.user_remove'](name, **db_args):
ret['comment'] = 'User {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
else:
ret['result'] = False
ret['comment'] = 'User {0} failed to be removed'.format(name)
return ret
else:
ret['comment'] = 'User {0} is not present, so it cannot ' \
'be removed'.format(name)
return ret
|
saltstack/salt
|
salt/states/zone.py
|
property_present
|
python
|
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
|
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L151-L199
|
[
"def _parse_value(value):\n '''Internal helper for parsing configuration values into python values'''\n if isinstance(value, bool):\n return 'true' if value else 'false'\n elif isinstance(value, six.string_types):\n # parse compacted notation to dict\n listparser = re.compile(r'''((?:[^,\"']|\"[^\"]*\"|'[^']*')+)''')\n\n value = value.strip()\n if value.startswith('[') and value.endswith(']'):\n return listparser.split(value[1:-1])[1::2]\n elif value.startswith('(') and value.endswith(')'):\n rval = {}\n for pair in listparser.split(value[1:-1])[1::2]:\n pair = pair.split('=')\n if '\"' in pair[1]:\n pair[1] = pair[1].replace('\"', '')\n if pair[1].isdigit():\n rval[pair[0]] = int(pair[1])\n elif pair[1] == 'true':\n rval[pair[0]] = True\n elif pair[1] == 'false':\n rval[pair[0]] = False\n else:\n rval[pair[0]] = pair[1]\n return rval\n else:\n if '\"' in value:\n value = value.replace('\"', '')\n if value.isdigit():\n return int(value)\n elif value == 'true':\n return True\n elif value == 'false':\n return False\n else:\n return value\n else:\n return value\n"
] |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
property_absent
|
python
|
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
|
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L202-L253
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
resource_present
|
python
|
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
|
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L256-L414
|
[
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def _parse_value(value):\n '''Internal helper for parsing configuration values into python values'''\n if isinstance(value, bool):\n return 'true' if value else 'false'\n elif isinstance(value, six.string_types):\n # parse compacted notation to dict\n listparser = re.compile(r'''((?:[^,\"']|\"[^\"]*\"|'[^']*')+)''')\n\n value = value.strip()\n if value.startswith('[') and value.endswith(']'):\n return listparser.split(value[1:-1])[1::2]\n elif value.startswith('(') and value.endswith(')'):\n rval = {}\n for pair in listparser.split(value[1:-1])[1::2]:\n pair = pair.split('=')\n if '\"' in pair[1]:\n pair[1] = pair[1].replace('\"', '')\n if pair[1].isdigit():\n rval[pair[0]] = int(pair[1])\n elif pair[1] == 'true':\n rval[pair[0]] = True\n elif pair[1] == 'false':\n rval[pair[0]] = False\n else:\n rval[pair[0]] = pair[1]\n return rval\n else:\n if '\"' in value:\n value = value.replace('\"', '')\n if value.isdigit():\n return int(value)\n elif value == 'true':\n return True\n elif value == 'false':\n return False\n else:\n return value\n else:\n return value\n"
] |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
resource_absent
|
python
|
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
|
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L417-L514
|
[
"def _parse_value(value):\n '''Internal helper for parsing configuration values into python values'''\n if isinstance(value, bool):\n return 'true' if value else 'false'\n elif isinstance(value, six.string_types):\n # parse compacted notation to dict\n listparser = re.compile(r'''((?:[^,\"']|\"[^\"]*\"|'[^']*')+)''')\n\n value = value.strip()\n if value.startswith('[') and value.endswith(']'):\n return listparser.split(value[1:-1])[1::2]\n elif value.startswith('(') and value.endswith(')'):\n rval = {}\n for pair in listparser.split(value[1:-1])[1::2]:\n pair = pair.split('=')\n if '\"' in pair[1]:\n pair[1] = pair[1].replace('\"', '')\n if pair[1].isdigit():\n rval[pair[0]] = int(pair[1])\n elif pair[1] == 'true':\n rval[pair[0]] = True\n elif pair[1] == 'false':\n rval[pair[0]] = False\n else:\n rval[pair[0]] = pair[1]\n return rval\n else:\n if '\"' in value:\n value = value.replace('\"', '')\n if value.isdigit():\n return int(value)\n elif value == 'true':\n return True\n elif value == 'false':\n return False\n else:\n return value\n else:\n return value\n"
] |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
booted
|
python
|
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
|
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L517-L568
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
halted
|
python
|
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
|
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L571-L622
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
export
|
python
|
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
|
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L625-L738
|
[
"def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\n"
] |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
import_
|
python
|
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
|
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L741-L839
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
present
|
python
|
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
|
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L842-L988
|
[
"def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):\n if strategy == 'smart':\n if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'):\n strategy = 'aggregate'\n else:\n strategy = 'recurse'\n\n if strategy == 'list':\n merged = merge_list(obj_a, obj_b)\n elif strategy == 'recurse':\n merged = merge_recurse(obj_a, obj_b, merge_lists)\n elif strategy == 'aggregate':\n #: level = 1 merge at least root data\n merged = merge_aggregate(obj_a, obj_b)\n elif strategy == 'overwrite':\n merged = merge_overwrite(obj_a, obj_b, merge_lists)\n elif strategy == 'none':\n # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse,\n # we just do not want to log an error\n merged = merge_recurse(obj_a, obj_b)\n else:\n log.warning(\n 'Unknown merging strategy \\'%s\\', fallback to recurse',\n strategy\n )\n merged = merge_recurse(obj_a, obj_b)\n\n return merged\n",
"def property_present(name, property, value):\n '''\n Ensure property has a certain value\n\n name : string\n name of the zone\n property : string\n name of property\n value : string\n value of property\n\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': None,\n 'comment': ''}\n\n ## sanitize input\n value = _parse_value(value)\n\n zones = __salt__['zoneadm.list'](installed=True, configured=True)\n if name in zones:\n ## zone exists\n zonecfg = __salt__['zonecfg.info'](name, show_all=True)\n if property not in zonecfg or zonecfg[property] != _parse_value(value):\n if __opts__['test']:\n ret['result'] = True\n else:\n # update property\n zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)\n ret['result'] = zonecfg_res['status']\n if 'messages' in zonecfg_res:\n ret['comment'] = zonecfg_res['message']\n if ret['result']:\n ret['changes'][property] = _parse_value(value)\n if ret['comment'] == '':\n ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)\n elif ret['comment'] == '':\n if ret['comment'] == '':\n ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)\n else:\n ret['result'] = True\n ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)\n else:\n ## zone does not exist\n ret['result'] = False\n ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)\n\n return ret\n",
"def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):\n '''\n Ensure resource exists with provided properties\n\n name : string\n name of the zone\n resource_type : string\n type of resource\n resource_selector_property : string\n unique resource identifier\n resource_selector_value : string\n value for resource selection\n kwargs : string|int|...\n resource properties\n\n .. warning::\n Both resource_selector_property and resource_selector_value must be\n provided, some properties like ``name`` are already reserved by salt in\n states.\n\n .. note::\n You can set both resource_selector_property and resource_selector_value\n to None for resources that do not require them.\n\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': None,\n 'comment': ''}\n\n # sanitize input\n kwargs = salt.utils.args.clean_kwargs(**kwargs)\n resource_selector_value = _parse_value(resource_selector_value)\n for k, v in kwargs.items():\n kwargs[k] = _parse_value(kwargs[k])\n\n zones = __salt__['zoneadm.list'](installed=True, configured=True)\n if name in zones:\n ## zone exists\n zonecfg = __salt__['zonecfg.info'](name, show_all=True)\n\n ## update kwargs\n zonecfg_kwargs = {}\n zonecfg_kwargs.update(kwargs)\n zonecfg_kwargs['zone'] = name\n zonecfg_kwargs['resource_type'] = resource_type\n zonecfg_kwargs['resource_selector'] = resource_selector_property\n if resource_selector_property:\n zonecfg_kwargs[resource_selector_property] = resource_selector_value\n\n ## check update or add\n if resource_type in zonecfg:\n for resource in zonecfg[resource_type]:\n if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:\n ret['result'] = True\n if resource_selector_property:\n ret['comment'] = 'the {0} resource {1} is up to date.'.format(\n resource_type,\n resource_selector_value,\n )\n else:\n ret['comment'] = 'the {0} resource is up to date.'.format(\n resource_type,\n )\n\n ## check if update reauired\n for key in kwargs:\n log.debug('zone.resource_preent - key=%s value=%s current_value=%s',\n key,\n resource[key] if key in resource else None,\n _parse_value(kwargs[key]),\n )\n # note: something odd with ncpus property, we fix it here for now\n if key == 'ncpus' and key in kwargs:\n kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))\n\n if key not in resource:\n ret['result'] = None\n elif resource[key] != _parse_value(kwargs[key]):\n ret['result'] = None\n\n ## do update\n if ret['result'] is None:\n if __opts__['test']:\n ret['result'] = True\n else:\n ## update resource\n zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)\n ret['result'] = zonecfg_res['status']\n if 'message' in zonecfg_res:\n ret['comment'] = zonecfg_res['message']\n\n if ret['result']:\n ret['changes'][resource_type] = {}\n if resource_selector_property:\n ret['changes'][resource_type][resource_selector_value] = {}\n for key in kwargs if ret['result'] else []:\n if resource_selector_property:\n ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])\n else:\n ret['changes'][resource_type][key] = _parse_value(kwargs[key])\n if ret['comment'] == '':\n if resource_selector_property:\n ret['comment'] = 'The {0} resource {1} was updated.'.format(\n resource_type,\n resource_selector_value,\n )\n else:\n ret['comment'] = 'The {0} resource was updated.'.format(\n resource_type,\n )\n elif ret['comment'] == '':\n if resource_selector_property:\n ret['comment'] = 'The {0} resource {1} was not updated.'.format(\n resource_type,\n resource_selector_value,\n )\n else:\n ret['comment'] = 'The {0} resource was not updated.'.format(\n resource_type,\n )\n if ret['result'] is None:\n ## add\n if __opts__['test']:\n ret['result'] = True\n else:\n ## add resource\n if 'resource_selector' in zonecfg_kwargs:\n del zonecfg_kwargs['resource_selector']\n zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)\n ret['result'] = zonecfg_res['status']\n if 'message' in zonecfg_res:\n ret['comment'] = zonecfg_res['message']\n\n if ret['result']:\n ret['changes'][resource_type] = {}\n if resource_selector_property:\n ret['changes'][resource_type][resource_selector_value] = {}\n for key in kwargs if ret['result'] else []:\n if resource_selector_property:\n ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])\n else:\n ret['changes'][resource_type][key] = _parse_value(kwargs[key])\n if ret['comment'] == '':\n ret['comment'] = 'The {0} resource {1} was added.'.format(\n resource_type,\n resource_selector_value,\n )\n elif ret['comment'] == '':\n ret['comment'] = 'The {0} resource {1} was not added.'.format(\n resource_type,\n resource_selector_value,\n )\n else:\n ## zone does not exist\n ret['result'] = False\n ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)\n\n return ret\n",
"def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):\n '''\n Ensure resource is absent\n\n name : string\n name of the zone\n resource_type : string\n type of resource\n resource_selector_property : string\n unique resource identifier\n resource_selector_value : string\n value for resource selection\n\n .. warning::\n Both resource_selector_property and resource_selector_value must be provided, some properties\n like ```name``` are already reserved by salt in there states.\n\n .. note::\n You can set both resource_selector_property and resource_selector_value to None for\n resources that do not require them.\n\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': None,\n 'comment': ''}\n\n # sanitize input\n if resource_selector_property:\n resource_selector_value = _parse_value(resource_selector_value)\n else:\n resource_selector_value = None\n\n zones = __salt__['zoneadm.list'](installed=True, configured=True)\n if name in zones:\n ## zone exists\n zonecfg = __salt__['zonecfg.info'](name, show_all=True)\n if resource_type in zonecfg:\n for resource in zonecfg[resource_type]:\n if __opts__['test']:\n ret['result'] = True\n elif not resource_selector_property:\n zonecfg_res = __salt__['zonecfg.remove_resource'](\n zone=name,\n resource_type=resource_type,\n resource_key=None,\n resource_value=None,\n )\n ret['result'] = zonecfg_res['status']\n if zonecfg_res['status']:\n ret['changes'][resource_type] = 'removed'\n if ret['comment'] == '':\n ret['comment'] = 'The {0} resource was removed.'.format(\n resource_type,\n )\n elif 'messages' in zonecfg_res:\n ret['comment'] = zonecfg_res['message']\n else:\n ret['comment'] = 'The {0} resource was not removed.'.format(\n resource_type,\n )\n elif resource[resource_selector_property] == resource_selector_value:\n zonecfg_res = __salt__['zonecfg.remove_resource'](\n zone=name,\n resource_type=resource_type,\n resource_key=resource_selector_property,\n resource_value=resource_selector_value,\n )\n ret['result'] = zonecfg_res['status']\n if zonecfg_res['status']:\n ret['changes'][resource_type] = {}\n ret['changes'][resource_type][resource_selector_value] = 'removed'\n if ret['comment'] == '':\n ret['comment'] = 'The {0} resource {1} was removed.'.format(\n resource_type,\n resource_selector_value,\n )\n elif 'messages' in zonecfg_res:\n ret['comment'] = zonecfg_res['message']\n else:\n ret['comment'] = 'The {0} resource {1} was not removed.'.format(\n resource_type,\n resource_selector_value,\n )\n\n # resource already absent\n if ret['result'] is None:\n ret['result'] = True\n ret['comment'] = 'The {0} resource {1} was absent.'.format(\n resource_type,\n resource_selector_value,\n )\n else:\n ## zone does not exist\n ret['result'] = False\n ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)\n\n return ret\n",
"def property_absent(name, property):\n '''\n Ensure property is absent\n\n name : string\n name of the zone\n property : string\n name of property\n\n .. note::\n This does a zoneacfg clear call. So the property may be reset to a default value!\n Does has the side effect of always having to be called.\n\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': None,\n 'comment': ''}\n\n zones = __salt__['zoneadm.list'](installed=True, configured=True)\n if name in zones:\n ## zone exists\n zonecfg = __salt__['zonecfg.info'](name, show_all=True)\n if property in zonecfg:\n if __opts__['test']:\n ret['result'] = True\n else:\n # clear property\n zonecfg_res = __salt__['zonecfg.clear_property'](name, property)\n zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)\n ret['result'] = zonecfg_res['status']\n if 'messages' in zonecfg_res:\n ret['comment'] = zonecfg_res['message']\n if ret['result']:\n if property not in zonecfg_new:\n ret['changes'][property] = None\n elif zonecfg[property] != zonecfg_new[property]:\n ret['changes'][property] = zonecfg_new[property]\n if ret['comment'] == '':\n ret['comment'] = 'The property {0} was cleared!'.format(property)\n elif ret['comment'] == '':\n if ret['comment'] == '':\n ret['comment'] = 'The property {0} did not get cleared!'.format(property)\n else:\n ret['result'] = True\n ret['comment'] = 'The property {0} does not exist!'.format(property)\n else:\n ## zone does not exist\n ret['result'] = False\n ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
absent
|
python
|
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
|
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L991-L1055
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
attached
|
python
|
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
|
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L1058-L1097
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
detached
|
python
|
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
|
Ensure zone is detached
name : string
name of the zone
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L1100-L1138
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
installed
|
python
|
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
|
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L1141-L1182
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/zone.py
|
uninstalled
|
python
|
def uninstalled(name):
'''
Ensure zone is uninstalled
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_uninstall = {'status': True}
else:
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already uninstalled.'.format(name)
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
|
Ensure zone is uninstalled
name : string
name of the zone
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zone.py#L1185-L1223
| null |
# -*- coding: utf-8 -*-
'''
Management of Solaris Zones
:maintainer: Jorge Schrauwen <sjorge@blackdot.be>
:maturity: new
:depends: salt.modules.zoneadm, salt.modules.zonecfg
:platform: solaris
.. versionadded:: 2017.7.0
Below are some examples of how to use this state.
Lets start with creating a zone and installing it.
.. code-block:: yaml
omipkg1_configuration:
zone.present:
- name: omipkg1
- brand: ipkg
- zonepath: /zones/omipkg1
- properties:
- autoboot: true
- ip-type: exclusive
- cpu-shares: 50
- resources:
- attr:
- name: owner
- value: Jorge Schrauwen
- type: string
- attr:
- name: description
- value: OmniOS ipkg zone for testing
- type: string
- capped-memory:
- physical: 64M
omipkg1_installation:
zone.installed:
- name: omipkg1
- require:
- zone: omipkg1_configuration
omipkg1_running:
zone.booted:
- name: omipkg1
- require:
- zone: omipkg1_installation
A zone without network access is not very useful. We could update
the zone.present state in the example above to add a network interface
or we could use a separate state for this.
.. code-block:: yaml
omipkg1_network:
zone.resource_present:
- name: omipkg1
- resource_type: net
- resource_selector_property: mac-addr
- resource_selector_value: "02:08:20:a2:a3:10"
- physical: znic1
- require:
- zone: omipkg1_configuration
Since this is a single tenant system having the owner attribute is pointless.
Let's remove that attribute.
.. note::
The following state run the omipkg1_configuration state will add it again!
If the entire configuration is managed it would be better to add resource_prune
and optionally the resource_selector_property properties to the resource.
.. code-block:: yaml
omipkg1_strip_owner:
zone.resource_present:
- name: omipkg1
- resource_type: attr
- resource_selector_property: name
- resource_selector_value: owner
- require:
- zone: omipkg1_configuration
Let's bump the zone's CPU shares a bit.
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should update it there instead.
.. code-block:: yaml
omipkg1_more_cpu:
zone.property_present:
- name: omipkg1
- property: cpu-shares
- value: 100
Or we can remove the limit altogether!
.. note::
The following state run the omipkg1_configuration state will set it to 50 again.
Update the entire zone configuration is managed you should set the
property to None (nothing after the :) instead.
.. code-block:: yaml
omipkg1_no_cpu:
zone.property_absent:
- name: omipkg1
- property: cpu-shares
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.files
from salt.modules.zonecfg import _parse_value, _zonecfg_resource_default_selectors
from salt.exceptions import CommandExecutionError
from salt.utils.odict import OrderedDict
from salt.utils.dictupdate import merge as merge_dict
log = logging.getLogger(__name__)
__func_alias__ = {
'import_': 'import',
}
# Define the state's virtual name
__virtualname__ = 'zone'
def __virtual__():
'''
Provides zone state on Solaris
'''
if 'zonecfg.create' in __salt__ and 'zoneadm.install' in __salt__:
return True
else:
return (
False,
'{0} state module can only be loaded on Solaris platforms'.format(
__virtualname__
)
)
def property_present(name, property, value):
'''
Ensure property has a certain value
name : string
name of the zone
property : string
name of property
value : string
value of property
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
## sanitize input
value = _parse_value(value)
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property not in zonecfg or zonecfg[property] != _parse_value(value):
if __opts__['test']:
ret['result'] = True
else:
# update property
zonecfg_res = __salt__['zonecfg.set_property'](name, property, value)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][property] = _parse_value(value)
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was updated to {1}.'.format(property, value)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} is was not updated to {1}!'.format(property, value)
else:
ret['result'] = True
ret['comment'] = 'The property {0} is already set to {1}.'.format(property, value)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def property_absent(name, property):
'''
Ensure property is absent
name : string
name of the zone
property : string
name of property
.. note::
This does a zoneacfg clear call. So the property may be reset to a default value!
Does has the side effect of always having to be called.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if property in zonecfg:
if __opts__['test']:
ret['result'] = True
else:
# clear property
zonecfg_res = __salt__['zonecfg.clear_property'](name, property)
zonecfg_new = __salt__['zonecfg.info'](name, show_all=True)
ret['result'] = zonecfg_res['status']
if 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
if property not in zonecfg_new:
ret['changes'][property] = None
elif zonecfg[property] != zonecfg_new[property]:
ret['changes'][property] = zonecfg_new[property]
if ret['comment'] == '':
ret['comment'] = 'The property {0} was cleared!'.format(property)
elif ret['comment'] == '':
if ret['comment'] == '':
ret['comment'] = 'The property {0} did not get cleared!'.format(property)
else:
ret['result'] = True
ret['comment'] = 'The property {0} does not exist!'.format(property)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_present(name, resource_type, resource_selector_property, resource_selector_value, **kwargs):
'''
Ensure resource exists with provided properties
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
kwargs : string|int|...
resource properties
.. warning::
Both resource_selector_property and resource_selector_value must be
provided, some properties like ``name`` are already reserved by salt in
states.
.. note::
You can set both resource_selector_property and resource_selector_value
to None for resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
kwargs = salt.utils.args.clean_kwargs(**kwargs)
resource_selector_value = _parse_value(resource_selector_value)
for k, v in kwargs.items():
kwargs[k] = _parse_value(kwargs[k])
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
## update kwargs
zonecfg_kwargs = {}
zonecfg_kwargs.update(kwargs)
zonecfg_kwargs['zone'] = name
zonecfg_kwargs['resource_type'] = resource_type
zonecfg_kwargs['resource_selector'] = resource_selector_property
if resource_selector_property:
zonecfg_kwargs[resource_selector_property] = resource_selector_value
## check update or add
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if not resource_selector_property or resource[resource_selector_property] == resource_selector_value:
ret['result'] = True
if resource_selector_property:
ret['comment'] = 'the {0} resource {1} is up to date.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'the {0} resource is up to date.'.format(
resource_type,
)
## check if update reauired
for key in kwargs:
log.debug('zone.resource_preent - key=%s value=%s current_value=%s',
key,
resource[key] if key in resource else None,
_parse_value(kwargs[key]),
)
# note: something odd with ncpus property, we fix it here for now
if key == 'ncpus' and key in kwargs:
kwargs[key] = '{0:.2f}'.format(float(kwargs[key]))
if key not in resource:
ret['result'] = None
elif resource[key] != _parse_value(kwargs[key]):
ret['result'] = None
## do update
if ret['result'] is None:
if __opts__['test']:
ret['result'] = True
else:
## update resource
zonecfg_res = __salt__['zonecfg.update_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was updated.'.format(
resource_type,
)
elif ret['comment'] == '':
if resource_selector_property:
ret['comment'] = 'The {0} resource {1} was not updated.'.format(
resource_type,
resource_selector_value,
)
else:
ret['comment'] = 'The {0} resource was not updated.'.format(
resource_type,
)
if ret['result'] is None:
## add
if __opts__['test']:
ret['result'] = True
else:
## add resource
if 'resource_selector' in zonecfg_kwargs:
del zonecfg_kwargs['resource_selector']
zonecfg_res = __salt__['zonecfg.add_resource'](**zonecfg_kwargs)
ret['result'] = zonecfg_res['status']
if 'message' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
if ret['result']:
ret['changes'][resource_type] = {}
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value] = {}
for key in kwargs if ret['result'] else []:
if resource_selector_property:
ret['changes'][resource_type][resource_selector_value][key] = _parse_value(kwargs[key])
else:
ret['changes'][resource_type][key] = _parse_value(kwargs[key])
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was added.'.format(
resource_type,
resource_selector_value,
)
elif ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was not added.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
'''
Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_property and resource_selector_value must be provided, some properties
like ```name``` are already reserved by salt in there states.
.. note::
You can set both resource_selector_property and resource_selector_value to None for
resources that do not require them.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# sanitize input
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_value = None
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
if resource_type in zonecfg:
for resource in zonecfg[resource_type]:
if __opts__['test']:
ret['result'] = True
elif not resource_selector_property:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=None,
resource_value=None,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource was removed.'.format(
resource_type,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource was not removed.'.format(
resource_type,
)
elif resource[resource_selector_property] == resource_selector_value:
zonecfg_res = __salt__['zonecfg.remove_resource'](
zone=name,
resource_type=resource_type,
resource_key=resource_selector_property,
resource_value=resource_selector_value,
)
ret['result'] = zonecfg_res['status']
if zonecfg_res['status']:
ret['changes'][resource_type] = {}
ret['changes'][resource_type][resource_selector_value] = 'removed'
if ret['comment'] == '':
ret['comment'] = 'The {0} resource {1} was removed.'.format(
resource_type,
resource_selector_value,
)
elif 'messages' in zonecfg_res:
ret['comment'] = zonecfg_res['message']
else:
ret['comment'] = 'The {0} resource {1} was not removed.'.format(
resource_type,
resource_selector_value,
)
# resource already absent
if ret['result'] is None:
ret['result'] = True
ret['comment'] = 'The {0} resource {1} was absent.'.format(
resource_type,
resource_selector_value,
)
else:
## zone does not exist
ret['result'] = False
ret['comment'] = 'The zone {0} is not in the configured, installed, or booted state.'.format(name)
return ret
def booted(name, single=False):
'''
Ensure zone is booted
name : string
name of the zone
single : boolean
boot in single usermode
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] == 'running':
## zone is running
ret['result'] = True
ret['comment'] = 'Zone {0} already booted'.format(name)
else:
## try and boot the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.boot'](name, single)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'booted'
ret['comment'] = 'Zone {0} booted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to boot {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed or booted state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def halted(name, graceful=True):
'''
Ensure zone is halted
name : string
name of the zone
graceful : boolean
use shutdown instead of halt if true
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True)
if name in zones:
## zone exists
if zones[name]['state'] != 'running':
## zone is not running
ret['result'] = True
ret['comment'] = 'Zone {0} already halted'.format(name)
else:
## try and halt the zone
if not __opts__['test']:
zoneadm_res = __salt__['zoneadm.shutdown'](name) if graceful else __salt__['zoneadm.halt'](name)
if __opts__['test'] or zoneadm_res['status']:
ret['result'] = True
ret['changes'][name] = 'halted'
ret['comment'] = 'Zone {0} halted'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to halt {0}'.format(name)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} is not in the installed state.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
zone,
name,
)
)
## note: a non existing zone is not running, we do not consider this a failure
ret['result'] = True
ret['comment'] = "\n".join(ret['comment'])
return ret
def export(name, path, replace=False):
'''
Export a zones configuration
name : string
name of the zone
path : string
path of file to export too.
replace : boolean
replace the file if it exists
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
## zone exists
if __opts__['test']:
## pretend we did the correct thing
ret['result'] = True
ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
name,
path,
)
ret['changes'][name] = 'exported'
if __salt__['file.file_exists'](path) and not replace:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
path,
name,
)
else:
## export and update file
cfg_tmp = salt.utils.files.mkstemp()
__salt__['zonecfg.export'](name, cfg_tmp)
if not __salt__['file.file_exists'](path):
## move cfg_tmp to path
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
if not cfg_diff:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
if replace:
try:
__salt__['file.move'](cfg_tmp, path)
except CommandExecutionError:
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
ret['result'] = False
ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
name,
path,
)
else:
ret['result'] = True
ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
name,
path,
)
ret['changes'][name] = 'exported'
else:
ret['result'] = False
ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
name,
path
)
if __salt__['file.file_exists'](cfg_tmp):
__salt__['file.remove'](cfg_tmp)
else:
## zone does not exist
ret['comment'] = []
ret['comment'].append(
'The zone {0} does not exist.'.format(name)
)
for zone in zones:
if zones[zone]['uuid'] == name:
ret['comment'].append(
'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
name,
path,
)
)
ret['result'] = False
ret['comment'] = "\n".join(ret['comment'])
return ret
def import_(name, path, mode='import', nodataset=False, brand_opts=None):
'''
Import a zones configuration
name : string
name of the zone
path : string
path of the configuration file to import
mode : string
either import, install, or attach
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
.. note::
The mode argument can be set to ``import``, ``install``, or ``attach``.
``import``: will only import the configuration
``install``: will import and then try to install the zone
``attach``: will import and then try to attach of the zone
.. code-block:: yaml
omipkg1:
zone.import:
- path: /foo/bar/baz
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name not in zones:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
ret['changes'][name] = 'imported'
else:
if __salt__['file.file_exists'](path):
res_import = __salt__['zonecfg.import'](name, path)
if not res_import['status']:
ret['result'] = False
ret['comment'] = 'Unable to import zone configuration for {0}!'.format(name)
else:
ret['result'] = True
ret['changes'][name] = 'imported'
ret['comment'] = 'Zone {0} was imported from {1}.'.format(
name,
path,
)
if mode.lower() == 'attach':
res_attach = __salt__['zoneadm.attach'](name, False, brand_opts)
ret['result'] = res_attach['status']
if res_attach['status']:
ret['changes'][name] = 'attached'
ret['comment'] = 'Zone {0} was attached from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
if mode.lower() == 'install':
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if res_install['status']:
ret['changes'][name] = 'installed'
ret['comment'] = 'Zone {0} was installed from {1}.'.format(
name,
path,
)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0} from {1}!'.format(
name,
path,
))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = False
ret['comment'] = 'The file {0} does not exists, unable to import!'.format(path)
else:
## zone exist
ret['result'] = True
ret['comment'] = 'Zone {0} already exists, not importing configuration.'.format(name)
return ret
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resources
.. note::
If the zone does not exist it will not be installed.
You can use the ```zone.installed``` state for this.
.. note::
Default resource selectors:
- fs: dir
- net: mac-addr
- device: match
- rctl: name
- attr: name
- dataset: name
- admin: user
.. warning::
Properties and resource will not be removed when they
are absent from the state!
For properties, simple set them to ```None```.
For resources, add the ```resource_prune``` property
and set it to ```True```. Also specify the
```resource_selector_property``` if the default is not
the one you want.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': []}
## sanitize defaults
if not properties:
properties = []
if not resources:
resources = []
properties.append(OrderedDict({"brand": brand}))
properties.append(OrderedDict({"zonepath": zonepath}))
zones = __salt__['zoneadm.list'](installed=True, configured=True)
## test mode only has limited support
if __opts__['test']:
ret['result'] = None
ret['comment'].append('Cannot determine of changes would happen to the zone {0}.'.format(name))
## create zone if needed
if name not in zones:
if __opts__['test']:
## we pretend we created the zone
res_create = {'status': True}
ret['comment'] = []
else:
## create and install
res_create = __salt__['zonecfg.create'](name, brand, zonepath)
if res_create['status']:
ret['result'] = True
ret['changes'][name] = 'created'
ret['comment'].append('The zone {0} was created.'.format(name))
if not __opts__['test']:
ret['result'] = True
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse property: %s', prop)
continue
for key, value in prop.items():
res = None
if not value:
res = property_absent(name, key)
elif value:
res = property_present(name, key, value)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'property' not in ret['changes']:
ret['changes']['property'] = {}
ret['changes']['property'] = merge_dict(ret['changes']['property'], res['changes'])
if isinstance(resources, list):
for resource in resources:
if not isinstance(prop, OrderedDict) or len(prop) != 1:
log.warning('zone.present - failed to parse resource: %s', resource)
continue
for key, value in resource.items():
zonecfg = __salt__['zonecfg.info'](name, show_all=True)
resource_cfg = {}
resource_cfg['resource_type'] = key
if isinstance(value, list):
for respv in value:
resource_cfg.update(dict(respv))
resource_prune = False
resource_selector_property = None
if 'resource_prune' in resource_cfg:
resource_prune = resource_cfg['resource_prune']
del resource_cfg['resource_prune']
if 'resource_selector_property' in resource_cfg:
resource_selector_property = resource_cfg['resource_selector_property']
del resource_cfg['resource_selector_property']
if not resource_selector_property and key in _zonecfg_resource_default_selectors:
resource_selector_property = _zonecfg_resource_default_selectors[key]
res = None
if resource_prune:
res = resource_absent(
name,
resource_cfg['resource_type'],
resource_selector_property=resource_selector_property,
resource_selector_value=resource_cfg[resource_selector_property] if resource_selector_property else None,
)
else:
resource_cfg['resource_selector_property'] = resource_selector_property
if resource_selector_property in resource_cfg:
resource_cfg['resource_selector_value'] = resource_cfg[resource_selector_property]
else:
resource_cfg['resource_selector_value'] = None
resource_cfg['name'] = name # we do this last because name can also be a attrib value
res = resource_present(**resource_cfg)
if res:
ret['result'] = ret['result'] if res['result'] else False
ret['comment'].append(res['comment'])
if res['changes']:
if 'resource' not in ret['changes']:
ret['changes']['resource'] = {}
ret['changes']['resource'] = merge_dict(ret['changes']['resource'], res['changes'])
if isinstance(ret['comment'], list):
ret['comment'] = "\n".join(ret['comment'])
return ret
def absent(name, uninstall=False):
'''
Ensure a zone is absent
name : string
name of the zone
uninstall : boolean
when true, uninstall instead of detaching the zone first.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if __opts__['test']:
ret['result'] = True
ret['changes'][name] = 'removed'
ret['comment'] = 'Zone {0} was removed.'.format(name)
else:
ret['result'] = True
if uninstall and zones[name]['state'] in ['running', 'installed']:
res_halt = __salt__['zoneadm.halt'](name)
res_uninstall = __salt__['zoneadm.uninstall'](name)
ret['result'] = res_uninstall['status']
if ret['result']:
ret['changes'][name] = 'uninstalled'
ret['comment'] = 'The zone {0} was uninstalled.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to uninstall zone {0}!'.format(name))
if 'message' in res_uninstall:
ret['comment'].append(res_uninstall['message'])
ret['comment'] = "\n".join(ret['comment'])
elif zones[name]['state'] == 'installed':
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
if ret['result']:
res_delete = __salt__['zonecfg.delete'](name)
ret['result'] = res_delete['status']
if ret['result']:
ret['changes'][name] = 'deleted'
ret['comment'] = 'The zone {0} was delete.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to delete zone {0}!'.format(name))
if 'message' in res_delete:
ret['comment'].append(res_delete['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'Zone {0} does not exist.'.format(name)
return ret
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_attach = {'status': True}
else:
res_attach = __salt__['zoneadm.attach'](name, force)
ret['result'] = res_attach['status']
if ret['result']:
ret['changes'][name] = 'attached'
ret['comment'] = 'The zone {0} was attached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to attach zone {0}!'.format(name))
if 'message' in res_attach:
ret['comment'].append(res_attach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already attached.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] != 'configured':
if __opts__['test']:
res_detach = {'status': True}
else:
res_detach = __salt__['zoneadm.detach'](name)
ret['result'] = res_detach['status']
if ret['result']:
ret['changes'][name] = 'detached'
ret['comment'] = 'The zone {0} was detached.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to detach zone {0}!'.format(name))
if 'message' in res_detach:
ret['comment'].append(res_detach['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already detached.'.format(name)
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret['result'] = True
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
def installed(name, nodataset=False, brand_opts=None):
'''
Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand_opts : boolean
brand specific options to pass
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zones[name]['state'] == 'configured':
if __opts__['test']:
res_install = {'status': True}
else:
res_install = __salt__['zoneadm.install'](name, nodataset, brand_opts)
ret['result'] = res_install['status']
if ret['result']:
ret['changes'][name] = 'installed'
ret['comment'] = 'The zone {0} was installed.'.format(name)
else:
ret['comment'] = []
ret['comment'].append('Failed to install zone {0}!'.format(name))
if 'message' in res_install:
ret['comment'].append(res_install['message'])
ret['comment'] = "\n".join(ret['comment'])
else:
ret['result'] = True
ret['comment'] = 'zone {0} already installed.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'zone {0} is not configured!'.format(name)
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/beacons/avahi_announce.py
|
validate
|
python
|
def validate(config):
'''
Validate the beacon configuration
'''
_config = {}
list(map(_config.update, config))
if not isinstance(config, list):
return False, ('Configuration for avahi_announce '
'beacon must be a list.')
elif not all(x in _config for x in ('servicetype',
'port',
'txt')):
return False, ('Configuration for avahi_announce beacon '
'must contain servicetype, port and txt items.')
return True, 'Valid beacon configuration.'
|
Validate the beacon configuration
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/avahi_announce.py#L60-L76
| null |
# -*- coding: utf-8 -*-
'''
Beacon to announce via avahi (zeroconf)
.. versionadded:: 2016.11.0
Dependencies
============
- python-avahi
- dbus-python
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import time
import salt.utils.stringutils
from salt.ext.six.moves import map
# Import 3rd Party libs
try:
import avahi
HAS_PYAVAHI = True
except ImportError:
HAS_PYAVAHI = False
try:
import dbus
from dbus import DBusException
BUS = dbus.SystemBus()
SERVER = dbus.Interface(BUS.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER),
avahi.DBUS_INTERFACE_SERVER)
GROUP = dbus.Interface(BUS.get_object(avahi.DBUS_NAME, SERVER.EntryGroupNew()),
avahi.DBUS_INTERFACE_ENTRY_GROUP)
HAS_DBUS = True
except (ImportError, NameError):
HAS_DBUS = False
except DBusException:
HAS_DBUS = False
log = logging.getLogger(__name__)
__virtualname__ = 'avahi_announce'
LAST_GRAINS = {}
def __virtual__():
if HAS_PYAVAHI:
if HAS_DBUS:
return __virtualname__
return False, 'The {0} beacon cannot be loaded. The ' \
'\'python-dbus\' dependency is missing.'.format(__virtualname__)
return False, 'The {0} beacon cannot be loaded. The ' \
'\'python-avahi\' dependency is missing.'.format(__virtualname__)
def _enforce_txt_record_maxlen(key, value):
'''
Enforces the TXT record maximum length of 255 characters.
TXT record length includes key, value, and '='.
:param str key: Key of the TXT record
:param str value: Value of the TXT record
:rtype: str
:return: The value of the TXT record. It may be truncated if it exceeds
the maximum permitted length. In case of truncation, '...' is
appended to indicate that the entire value is not present.
'''
# Add 1 for '=' seperator between key and value
if len(key) + len(value) + 1 > 255:
# 255 - 3 ('...') - 1 ('=') = 251
return value[:251 - len(key)] + '...'
return value
def beacon(config):
'''
Broadcast values via zeroconf
If the announced values are static, it is advised to set run_once: True
(do not poll) on the beacon configuration.
The following are required configuration settings:
- ``servicetype`` - The service type to announce
- ``port`` - The port of the service to announce
- ``txt`` - The TXT record of the service being announced as a dict. Grains
can be used to define TXT values using one of following two formats:
- ``grains.<grain_name>``
- ``grains.<grain_name>[i]`` where i is an integer representing the
index of the grain to use. If the grain is not a list, the index is
ignored.
The following are optional configuration settings:
- ``servicename`` - Set the name of the service. Will use the hostname from
the minion's ``host`` grain if this value is not set.
- ``reset_on_change`` - If ``True`` and there is a change in TXT records
detected, it will stop announcing the service and then restart announcing
the service. This interruption in service announcement may be desirable
if the client relies on changes in the browse records to update its cache
of TXT records. Defaults to ``False``.
- ``reset_wait`` - The number of seconds to wait after announcement stops
announcing and before it restarts announcing in the case where there is a
change in TXT records detected and ``reset_on_change`` is ``True``.
Defaults to ``0``.
- ``copy_grains`` - If ``True``, Salt will copy the grains passed into the
beacon when it backs them up to check for changes on the next iteration.
Normally, instead of copy, it would use straight value assignment. This
will allow detection of changes to grains where the grains are modified
in-place instead of completely replaced. In-place grains changes are not
currently done in the main Salt code but may be done due to a custom
plug-in. Defaults to ``False``.
Example Config
.. code-block:: yaml
beacons:
avahi_announce:
- run_once: True
- servicetype: _demo._tcp
- port: 1234
- txt:
ProdName: grains.productname
SerialNo: grains.serialnumber
Comments: 'this is a test'
'''
ret = []
changes = {}
txt = {}
global LAST_GRAINS
_config = {}
list(map(_config.update, config))
if 'servicename' in _config:
servicename = _config['servicename']
else:
servicename = __grains__['host']
# Check for hostname change
if LAST_GRAINS and LAST_GRAINS['host'] != servicename:
changes['servicename'] = servicename
if LAST_GRAINS and _config.get('reset_on_change', False):
# Check for IP address change in the case when we reset on change
if LAST_GRAINS.get('ipv4', []) != __grains__.get('ipv4', []):
changes['ipv4'] = __grains__.get('ipv4', [])
if LAST_GRAINS.get('ipv6', []) != __grains__.get('ipv6', []):
changes['ipv6'] = __grains__.get('ipv6', [])
for item in _config['txt']:
changes_key = 'txt.' + salt.utils.stringutils.to_unicode(item)
if _config['txt'][item].startswith('grains.'):
grain = _config['txt'][item][7:]
grain_index = None
square_bracket = grain.find('[')
if square_bracket != -1 and grain[-1] == ']':
grain_index = int(grain[square_bracket+1:-1])
grain = grain[:square_bracket]
grain_value = __grains__.get(grain, '')
if isinstance(grain_value, list):
if grain_index is not None:
grain_value = grain_value[grain_index]
else:
grain_value = ','.join(grain_value)
txt[item] = _enforce_txt_record_maxlen(item, grain_value)
if LAST_GRAINS and (LAST_GRAINS.get(grain, '') != __grains__.get(grain, '')):
changes[changes_key] = txt[item]
else:
txt[item] = _enforce_txt_record_maxlen(item, _config['txt'][item])
if not LAST_GRAINS:
changes[changes_key] = txt[item]
if changes:
if not LAST_GRAINS:
changes['servicename'] = servicename
changes['servicetype'] = _config['servicetype']
changes['port'] = _config['port']
changes['ipv4'] = __grains__.get('ipv4', [])
changes['ipv6'] = __grains__.get('ipv6', [])
GROUP.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0),
servicename, _config['servicetype'], '', '',
dbus.UInt16(_config['port']), avahi.dict_to_txt_array(txt))
GROUP.Commit()
elif _config.get('reset_on_change', False) or 'servicename' in changes:
# A change in 'servicename' requires a reset because we can only
# directly update TXT records
GROUP.Reset()
reset_wait = _config.get('reset_wait', 0)
if reset_wait > 0:
time.sleep(reset_wait)
GROUP.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0),
servicename, _config['servicetype'], '', '',
dbus.UInt16(_config['port']), avahi.dict_to_txt_array(txt))
GROUP.Commit()
else:
GROUP.UpdateServiceTxt(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0),
servicename, _config['servicetype'], '',
avahi.dict_to_txt_array(txt))
ret.append({'tag': 'result', 'changes': changes})
if _config.get('copy_grains', False):
LAST_GRAINS = __grains__.copy()
else:
LAST_GRAINS = __grains__
return ret
|
saltstack/salt
|
salt/beacons/avahi_announce.py
|
beacon
|
python
|
def beacon(config):
'''
Broadcast values via zeroconf
If the announced values are static, it is advised to set run_once: True
(do not poll) on the beacon configuration.
The following are required configuration settings:
- ``servicetype`` - The service type to announce
- ``port`` - The port of the service to announce
- ``txt`` - The TXT record of the service being announced as a dict. Grains
can be used to define TXT values using one of following two formats:
- ``grains.<grain_name>``
- ``grains.<grain_name>[i]`` where i is an integer representing the
index of the grain to use. If the grain is not a list, the index is
ignored.
The following are optional configuration settings:
- ``servicename`` - Set the name of the service. Will use the hostname from
the minion's ``host`` grain if this value is not set.
- ``reset_on_change`` - If ``True`` and there is a change in TXT records
detected, it will stop announcing the service and then restart announcing
the service. This interruption in service announcement may be desirable
if the client relies on changes in the browse records to update its cache
of TXT records. Defaults to ``False``.
- ``reset_wait`` - The number of seconds to wait after announcement stops
announcing and before it restarts announcing in the case where there is a
change in TXT records detected and ``reset_on_change`` is ``True``.
Defaults to ``0``.
- ``copy_grains`` - If ``True``, Salt will copy the grains passed into the
beacon when it backs them up to check for changes on the next iteration.
Normally, instead of copy, it would use straight value assignment. This
will allow detection of changes to grains where the grains are modified
in-place instead of completely replaced. In-place grains changes are not
currently done in the main Salt code but may be done due to a custom
plug-in. Defaults to ``False``.
Example Config
.. code-block:: yaml
beacons:
avahi_announce:
- run_once: True
- servicetype: _demo._tcp
- port: 1234
- txt:
ProdName: grains.productname
SerialNo: grains.serialnumber
Comments: 'this is a test'
'''
ret = []
changes = {}
txt = {}
global LAST_GRAINS
_config = {}
list(map(_config.update, config))
if 'servicename' in _config:
servicename = _config['servicename']
else:
servicename = __grains__['host']
# Check for hostname change
if LAST_GRAINS and LAST_GRAINS['host'] != servicename:
changes['servicename'] = servicename
if LAST_GRAINS and _config.get('reset_on_change', False):
# Check for IP address change in the case when we reset on change
if LAST_GRAINS.get('ipv4', []) != __grains__.get('ipv4', []):
changes['ipv4'] = __grains__.get('ipv4', [])
if LAST_GRAINS.get('ipv6', []) != __grains__.get('ipv6', []):
changes['ipv6'] = __grains__.get('ipv6', [])
for item in _config['txt']:
changes_key = 'txt.' + salt.utils.stringutils.to_unicode(item)
if _config['txt'][item].startswith('grains.'):
grain = _config['txt'][item][7:]
grain_index = None
square_bracket = grain.find('[')
if square_bracket != -1 and grain[-1] == ']':
grain_index = int(grain[square_bracket+1:-1])
grain = grain[:square_bracket]
grain_value = __grains__.get(grain, '')
if isinstance(grain_value, list):
if grain_index is not None:
grain_value = grain_value[grain_index]
else:
grain_value = ','.join(grain_value)
txt[item] = _enforce_txt_record_maxlen(item, grain_value)
if LAST_GRAINS and (LAST_GRAINS.get(grain, '') != __grains__.get(grain, '')):
changes[changes_key] = txt[item]
else:
txt[item] = _enforce_txt_record_maxlen(item, _config['txt'][item])
if not LAST_GRAINS:
changes[changes_key] = txt[item]
if changes:
if not LAST_GRAINS:
changes['servicename'] = servicename
changes['servicetype'] = _config['servicetype']
changes['port'] = _config['port']
changes['ipv4'] = __grains__.get('ipv4', [])
changes['ipv6'] = __grains__.get('ipv6', [])
GROUP.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0),
servicename, _config['servicetype'], '', '',
dbus.UInt16(_config['port']), avahi.dict_to_txt_array(txt))
GROUP.Commit()
elif _config.get('reset_on_change', False) or 'servicename' in changes:
# A change in 'servicename' requires a reset because we can only
# directly update TXT records
GROUP.Reset()
reset_wait = _config.get('reset_wait', 0)
if reset_wait > 0:
time.sleep(reset_wait)
GROUP.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0),
servicename, _config['servicetype'], '', '',
dbus.UInt16(_config['port']), avahi.dict_to_txt_array(txt))
GROUP.Commit()
else:
GROUP.UpdateServiceTxt(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0),
servicename, _config['servicetype'], '',
avahi.dict_to_txt_array(txt))
ret.append({'tag': 'result', 'changes': changes})
if _config.get('copy_grains', False):
LAST_GRAINS = __grains__.copy()
else:
LAST_GRAINS = __grains__
return ret
|
Broadcast values via zeroconf
If the announced values are static, it is advised to set run_once: True
(do not poll) on the beacon configuration.
The following are required configuration settings:
- ``servicetype`` - The service type to announce
- ``port`` - The port of the service to announce
- ``txt`` - The TXT record of the service being announced as a dict. Grains
can be used to define TXT values using one of following two formats:
- ``grains.<grain_name>``
- ``grains.<grain_name>[i]`` where i is an integer representing the
index of the grain to use. If the grain is not a list, the index is
ignored.
The following are optional configuration settings:
- ``servicename`` - Set the name of the service. Will use the hostname from
the minion's ``host`` grain if this value is not set.
- ``reset_on_change`` - If ``True`` and there is a change in TXT records
detected, it will stop announcing the service and then restart announcing
the service. This interruption in service announcement may be desirable
if the client relies on changes in the browse records to update its cache
of TXT records. Defaults to ``False``.
- ``reset_wait`` - The number of seconds to wait after announcement stops
announcing and before it restarts announcing in the case where there is a
change in TXT records detected and ``reset_on_change`` is ``True``.
Defaults to ``0``.
- ``copy_grains`` - If ``True``, Salt will copy the grains passed into the
beacon when it backs them up to check for changes on the next iteration.
Normally, instead of copy, it would use straight value assignment. This
will allow detection of changes to grains where the grains are modified
in-place instead of completely replaced. In-place grains changes are not
currently done in the main Salt code but may be done due to a custom
plug-in. Defaults to ``False``.
Example Config
.. code-block:: yaml
beacons:
avahi_announce:
- run_once: True
- servicetype: _demo._tcp
- port: 1234
- txt:
ProdName: grains.productname
SerialNo: grains.serialnumber
Comments: 'this is a test'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/avahi_announce.py#L99-L236
| null |
# -*- coding: utf-8 -*-
'''
Beacon to announce via avahi (zeroconf)
.. versionadded:: 2016.11.0
Dependencies
============
- python-avahi
- dbus-python
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import time
import salt.utils.stringutils
from salt.ext.six.moves import map
# Import 3rd Party libs
try:
import avahi
HAS_PYAVAHI = True
except ImportError:
HAS_PYAVAHI = False
try:
import dbus
from dbus import DBusException
BUS = dbus.SystemBus()
SERVER = dbus.Interface(BUS.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER),
avahi.DBUS_INTERFACE_SERVER)
GROUP = dbus.Interface(BUS.get_object(avahi.DBUS_NAME, SERVER.EntryGroupNew()),
avahi.DBUS_INTERFACE_ENTRY_GROUP)
HAS_DBUS = True
except (ImportError, NameError):
HAS_DBUS = False
except DBusException:
HAS_DBUS = False
log = logging.getLogger(__name__)
__virtualname__ = 'avahi_announce'
LAST_GRAINS = {}
def __virtual__():
if HAS_PYAVAHI:
if HAS_DBUS:
return __virtualname__
return False, 'The {0} beacon cannot be loaded. The ' \
'\'python-dbus\' dependency is missing.'.format(__virtualname__)
return False, 'The {0} beacon cannot be loaded. The ' \
'\'python-avahi\' dependency is missing.'.format(__virtualname__)
def validate(config):
'''
Validate the beacon configuration
'''
_config = {}
list(map(_config.update, config))
if not isinstance(config, list):
return False, ('Configuration for avahi_announce '
'beacon must be a list.')
elif not all(x in _config for x in ('servicetype',
'port',
'txt')):
return False, ('Configuration for avahi_announce beacon '
'must contain servicetype, port and txt items.')
return True, 'Valid beacon configuration.'
def _enforce_txt_record_maxlen(key, value):
'''
Enforces the TXT record maximum length of 255 characters.
TXT record length includes key, value, and '='.
:param str key: Key of the TXT record
:param str value: Value of the TXT record
:rtype: str
:return: The value of the TXT record. It may be truncated if it exceeds
the maximum permitted length. In case of truncation, '...' is
appended to indicate that the entire value is not present.
'''
# Add 1 for '=' seperator between key and value
if len(key) + len(value) + 1 > 255:
# 255 - 3 ('...') - 1 ('=') = 251
return value[:251 - len(key)] + '...'
return value
|
saltstack/salt
|
salt/states/tomcat.py
|
war_deployed
|
python
|
def war_deployed(name,
war,
force=False,
url='http://localhost:8080/manager',
timeout=180,
temp_war_location=None,
version=True):
'''
Enforce that the WAR will be deployed and started in the context path,
while making use of WAR versions in the filename.
.. note::
For more info about Tomcats file paths and context naming, please see
http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Naming
name
The context path to deploy (incl. forward slash) the WAR to.
war
Absolute path to WAR file (should be accessible by the user running
Tomcat) or a path supported by the ``salt.modules.cp.get_url`` function.
force : False
Force deployment even if the version strings are the same.
Disabled by default.
url : http://localhost:8080/manager
The URL of the Tomcat Web Application Manager.
timeout : 180
Timeout for HTTP requests to the Tomcat Manager.
temp_war_location : None
Use another location to temporarily copy the WAR file to.
By default the system's temp directory is used.
version : ''
Specify the WAR version. If this argument is provided, it overrides
the version encoded in the WAR file name, if one is present.
.. versionadded:: 2015.8.6
Use ``False`` or blank value to prevent guessing the version and keeping it blank.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
jenkins:
tomcat.war_deployed:
- name: /salt-powered-jenkins
- war: salt://jenkins-1.2.4.war
- require:
- service: application-service
.. note::
Be aware that in the above example the WAR ``jenkins-1.2.4.war`` will
be deployed to the context path ``salt-powered-jenkins##1.2.4``. To avoid this
either specify a version yourself, or set version to ``False``.
'''
# Prepare
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
# if version is defined or False, we don't want to overwrite
if version is True:
version = __salt__['tomcat.extract_war_version'](war) or ''
elif not version:
version = ''
webapps = __salt__['tomcat.ls'](url, timeout)
deploy = False
undeploy = False
status = True
# Gathered/specified new WAR version string
specified_ver = 'version {0}'.format(version) if version else 'no version'
# Determine what to do
try:
# Printed version strings, here to throw exception if no webapps[name]
current_ver = 'version ' + webapps[name]['version'] \
if webapps[name]['version'] else 'no version'
# `endswith` on the supposed string will cause Exception if empty
if (not webapps[name]['version'].endswith(version)
or (version == '' and webapps[name]['version'] != version)
or force):
deploy = True
undeploy = True
ret['changes']['undeploy'] = ('undeployed {0} with {1}'.
format(name, current_ver))
ret['changes']['deploy'] = ('will deploy {0} with {1}'.
format(name, specified_ver))
else:
deploy = False
ret['comment'] = ('{0} with {1} is already deployed'.
format(name, specified_ver))
if webapps[name]['mode'] != 'running':
ret['changes']['start'] = 'starting {0}'.format(name)
status = False
else:
return ret
except Exception:
deploy = True
ret['changes']['deploy'] = ('deployed {0} with {1}'.
format(name, specified_ver))
# Test
if __opts__['test']:
ret['result'] = None
return ret
# make sure the webapp is up if deployed
if deploy is False:
if status is False:
ret['comment'] = __salt__['tomcat.start'](name, url,
timeout=timeout)
ret['result'] = ret['comment'].startswith('OK')
return ret
# Undeploy
if undeploy:
un = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if un.startswith('FAIL'):
ret['result'] = False
ret['comment'] = un
return ret
# Deploy
deploy_res = __salt__['tomcat.deploy_war'](war,
name,
'yes',
url,
__env__,
timeout,
temp_war_location=temp_war_location,
version=version)
# Return
if deploy_res.startswith('OK'):
ret['result'] = True
ret['comment'] = six.text_type(__salt__['tomcat.ls'](url, timeout)[name])
ret['changes']['deploy'] = ('deployed {0} with {1}'.
format(name, specified_ver))
else:
ret['result'] = False
ret['comment'] = deploy_res
ret['changes'].pop('deploy')
return ret
|
Enforce that the WAR will be deployed and started in the context path,
while making use of WAR versions in the filename.
.. note::
For more info about Tomcats file paths and context naming, please see
http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Naming
name
The context path to deploy (incl. forward slash) the WAR to.
war
Absolute path to WAR file (should be accessible by the user running
Tomcat) or a path supported by the ``salt.modules.cp.get_url`` function.
force : False
Force deployment even if the version strings are the same.
Disabled by default.
url : http://localhost:8080/manager
The URL of the Tomcat Web Application Manager.
timeout : 180
Timeout for HTTP requests to the Tomcat Manager.
temp_war_location : None
Use another location to temporarily copy the WAR file to.
By default the system's temp directory is used.
version : ''
Specify the WAR version. If this argument is provided, it overrides
the version encoded in the WAR file name, if one is present.
.. versionadded:: 2015.8.6
Use ``False`` or blank value to prevent guessing the version and keeping it blank.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
jenkins:
tomcat.war_deployed:
- name: /salt-powered-jenkins
- war: salt://jenkins-1.2.4.war
- require:
- service: application-service
.. note::
Be aware that in the above example the WAR ``jenkins-1.2.4.war`` will
be deployed to the context path ``salt-powered-jenkins##1.2.4``. To avoid this
either specify a version yourself, or set version to ``False``.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/tomcat.py#L73-L222
| null |
# -*- coding: utf-8 -*-
'''
Manage Apache Tomcat web applications
=====================================
.. note::
This state requires the Tomcat Manager webapp to be installed and running.
The following grains/pillars must be set for communication with Tomcat Manager
to work:
.. code-block:: yaml
tomcat-manager:
user: 'tomcat-manager'
passwd: 'Passw0rd'
Configuring Tomcat Manager
--------------------------
To manage webapps via the Tomcat Manager, you'll need to configure
a valid user in the file ``conf/tomcat-users.xml``.
.. code-block:: xml
:caption: conf/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat-manager" password="Passw0rd" roles="manager-script"/>
</tomcat-users>
Notes
-----
- Using multiple versions (aka. parallel deployments) on the same context
path is not supported.
- More information about the Tomcat Manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- If you use only this module for deployments you might want to restrict
access to the manager so it's only accessible via localhost.
For more info: http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Last tested on:
Tomcat Version:
Apache Tomcat/7.0.54
JVM Vendor:
Oracle Corporation
JVM Version:
1.8.0_101-b13
OS Architecture:
amd64
OS Name:
Linux
OS Version:
3.10.0-327.22.2.el7.x86_64
'''
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext import six
# Private
def __virtual__():
'''
Load if the module tomcat exists
'''
return 'tomcat' if 'tomcat.status' in __salt__ else False
# Functions
def wait(name, url='http://localhost:8080/manager', timeout=180):
'''
Wait for the Tomcat Manager to load.
Notice that if tomcat is not running we won't wait for it start and the
state will fail. This state can be required in the tomcat.war_deployed
state to make sure tomcat is running and that the manager is running as
well and ready for deployment.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
tomcat-service:
service.running:
- name: tomcat
- enable: True
wait-for-tomcatmanager:
tomcat.wait:
- timeout: 300
- require:
- service: tomcat-service
jenkins:
tomcat.war_deployed:
- name: /ran
- war: salt://jenkins-1.2.4.war
- require:
- tomcat: wait-for-tomcatmanager
'''
result = __salt__['tomcat.status'](url, timeout)
ret = {'name': name,
'result': result,
'changes': {},
'comment': ('tomcat manager is ready' if result
else 'tomcat manager is not ready')
}
return ret
def mod_watch(name, url='http://localhost:8080/manager', timeout=180):
'''
The tomcat watcher, called to invoke the watch command.
When called, it will reload the webapp in question
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
msg = __salt__['tomcat.reload'](name, url, timeout)
result = msg.startswith('OK')
ret = {'name': name,
'result': result,
'changes': {name: result},
'comment': msg
}
return ret
def undeployed(name,
url='http://localhost:8080/manager',
timeout=180):
'''
Enforce that the WAR will be undeployed from the server
name
The context path to undeploy.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
jenkins:
tomcat.undeployed:
- name: /ran
- require:
- service: application-service
'''
# Prepare
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not __salt__['tomcat.status'](url, timeout):
ret['comment'] = 'Tomcat Manager does not respond'
ret['result'] = False
return ret
try:
version = __salt__['tomcat.ls'](url, timeout)[name]['version']
ret['changes'] = {'undeploy': version}
except KeyError:
return ret
# Test
if __opts__['test']:
ret['result'] = None
return ret
undeploy = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if undeploy.startswith('FAIL'):
ret['result'] = False
ret['comment'] = undeploy
return ret
return ret
|
saltstack/salt
|
salt/states/tomcat.py
|
wait
|
python
|
def wait(name, url='http://localhost:8080/manager', timeout=180):
'''
Wait for the Tomcat Manager to load.
Notice that if tomcat is not running we won't wait for it start and the
state will fail. This state can be required in the tomcat.war_deployed
state to make sure tomcat is running and that the manager is running as
well and ready for deployment.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
tomcat-service:
service.running:
- name: tomcat
- enable: True
wait-for-tomcatmanager:
tomcat.wait:
- timeout: 300
- require:
- service: tomcat-service
jenkins:
tomcat.war_deployed:
- name: /ran
- war: salt://jenkins-1.2.4.war
- require:
- tomcat: wait-for-tomcatmanager
'''
result = __salt__['tomcat.status'](url, timeout)
ret = {'name': name,
'result': result,
'changes': {},
'comment': ('tomcat manager is ready' if result
else 'tomcat manager is not ready')
}
return ret
|
Wait for the Tomcat Manager to load.
Notice that if tomcat is not running we won't wait for it start and the
state will fail. This state can be required in the tomcat.war_deployed
state to make sure tomcat is running and that the manager is running as
well and ready for deployment.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
tomcat-service:
service.running:
- name: tomcat
- enable: True
wait-for-tomcatmanager:
tomcat.wait:
- timeout: 300
- require:
- service: tomcat-service
jenkins:
tomcat.war_deployed:
- name: /ran
- war: salt://jenkins-1.2.4.war
- require:
- tomcat: wait-for-tomcatmanager
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/tomcat.py#L225-L270
| null |
# -*- coding: utf-8 -*-
'''
Manage Apache Tomcat web applications
=====================================
.. note::
This state requires the Tomcat Manager webapp to be installed and running.
The following grains/pillars must be set for communication with Tomcat Manager
to work:
.. code-block:: yaml
tomcat-manager:
user: 'tomcat-manager'
passwd: 'Passw0rd'
Configuring Tomcat Manager
--------------------------
To manage webapps via the Tomcat Manager, you'll need to configure
a valid user in the file ``conf/tomcat-users.xml``.
.. code-block:: xml
:caption: conf/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat-manager" password="Passw0rd" roles="manager-script"/>
</tomcat-users>
Notes
-----
- Using multiple versions (aka. parallel deployments) on the same context
path is not supported.
- More information about the Tomcat Manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- If you use only this module for deployments you might want to restrict
access to the manager so it's only accessible via localhost.
For more info: http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Last tested on:
Tomcat Version:
Apache Tomcat/7.0.54
JVM Vendor:
Oracle Corporation
JVM Version:
1.8.0_101-b13
OS Architecture:
amd64
OS Name:
Linux
OS Version:
3.10.0-327.22.2.el7.x86_64
'''
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext import six
# Private
def __virtual__():
'''
Load if the module tomcat exists
'''
return 'tomcat' if 'tomcat.status' in __salt__ else False
# Functions
def war_deployed(name,
war,
force=False,
url='http://localhost:8080/manager',
timeout=180,
temp_war_location=None,
version=True):
'''
Enforce that the WAR will be deployed and started in the context path,
while making use of WAR versions in the filename.
.. note::
For more info about Tomcats file paths and context naming, please see
http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Naming
name
The context path to deploy (incl. forward slash) the WAR to.
war
Absolute path to WAR file (should be accessible by the user running
Tomcat) or a path supported by the ``salt.modules.cp.get_url`` function.
force : False
Force deployment even if the version strings are the same.
Disabled by default.
url : http://localhost:8080/manager
The URL of the Tomcat Web Application Manager.
timeout : 180
Timeout for HTTP requests to the Tomcat Manager.
temp_war_location : None
Use another location to temporarily copy the WAR file to.
By default the system's temp directory is used.
version : ''
Specify the WAR version. If this argument is provided, it overrides
the version encoded in the WAR file name, if one is present.
.. versionadded:: 2015.8.6
Use ``False`` or blank value to prevent guessing the version and keeping it blank.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
jenkins:
tomcat.war_deployed:
- name: /salt-powered-jenkins
- war: salt://jenkins-1.2.4.war
- require:
- service: application-service
.. note::
Be aware that in the above example the WAR ``jenkins-1.2.4.war`` will
be deployed to the context path ``salt-powered-jenkins##1.2.4``. To avoid this
either specify a version yourself, or set version to ``False``.
'''
# Prepare
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
# if version is defined or False, we don't want to overwrite
if version is True:
version = __salt__['tomcat.extract_war_version'](war) or ''
elif not version:
version = ''
webapps = __salt__['tomcat.ls'](url, timeout)
deploy = False
undeploy = False
status = True
# Gathered/specified new WAR version string
specified_ver = 'version {0}'.format(version) if version else 'no version'
# Determine what to do
try:
# Printed version strings, here to throw exception if no webapps[name]
current_ver = 'version ' + webapps[name]['version'] \
if webapps[name]['version'] else 'no version'
# `endswith` on the supposed string will cause Exception if empty
if (not webapps[name]['version'].endswith(version)
or (version == '' and webapps[name]['version'] != version)
or force):
deploy = True
undeploy = True
ret['changes']['undeploy'] = ('undeployed {0} with {1}'.
format(name, current_ver))
ret['changes']['deploy'] = ('will deploy {0} with {1}'.
format(name, specified_ver))
else:
deploy = False
ret['comment'] = ('{0} with {1} is already deployed'.
format(name, specified_ver))
if webapps[name]['mode'] != 'running':
ret['changes']['start'] = 'starting {0}'.format(name)
status = False
else:
return ret
except Exception:
deploy = True
ret['changes']['deploy'] = ('deployed {0} with {1}'.
format(name, specified_ver))
# Test
if __opts__['test']:
ret['result'] = None
return ret
# make sure the webapp is up if deployed
if deploy is False:
if status is False:
ret['comment'] = __salt__['tomcat.start'](name, url,
timeout=timeout)
ret['result'] = ret['comment'].startswith('OK')
return ret
# Undeploy
if undeploy:
un = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if un.startswith('FAIL'):
ret['result'] = False
ret['comment'] = un
return ret
# Deploy
deploy_res = __salt__['tomcat.deploy_war'](war,
name,
'yes',
url,
__env__,
timeout,
temp_war_location=temp_war_location,
version=version)
# Return
if deploy_res.startswith('OK'):
ret['result'] = True
ret['comment'] = six.text_type(__salt__['tomcat.ls'](url, timeout)[name])
ret['changes']['deploy'] = ('deployed {0} with {1}'.
format(name, specified_ver))
else:
ret['result'] = False
ret['comment'] = deploy_res
ret['changes'].pop('deploy')
return ret
def mod_watch(name, url='http://localhost:8080/manager', timeout=180):
'''
The tomcat watcher, called to invoke the watch command.
When called, it will reload the webapp in question
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
msg = __salt__['tomcat.reload'](name, url, timeout)
result = msg.startswith('OK')
ret = {'name': name,
'result': result,
'changes': {name: result},
'comment': msg
}
return ret
def undeployed(name,
url='http://localhost:8080/manager',
timeout=180):
'''
Enforce that the WAR will be undeployed from the server
name
The context path to undeploy.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
jenkins:
tomcat.undeployed:
- name: /ran
- require:
- service: application-service
'''
# Prepare
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not __salt__['tomcat.status'](url, timeout):
ret['comment'] = 'Tomcat Manager does not respond'
ret['result'] = False
return ret
try:
version = __salt__['tomcat.ls'](url, timeout)[name]['version']
ret['changes'] = {'undeploy': version}
except KeyError:
return ret
# Test
if __opts__['test']:
ret['result'] = None
return ret
undeploy = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if undeploy.startswith('FAIL'):
ret['result'] = False
ret['comment'] = undeploy
return ret
return ret
|
saltstack/salt
|
salt/states/tomcat.py
|
mod_watch
|
python
|
def mod_watch(name, url='http://localhost:8080/manager', timeout=180):
'''
The tomcat watcher, called to invoke the watch command.
When called, it will reload the webapp in question
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
msg = __salt__['tomcat.reload'](name, url, timeout)
result = msg.startswith('OK')
ret = {'name': name,
'result': result,
'changes': {name: result},
'comment': msg
}
return ret
|
The tomcat watcher, called to invoke the watch command.
When called, it will reload the webapp in question
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/tomcat.py#L273-L294
| null |
# -*- coding: utf-8 -*-
'''
Manage Apache Tomcat web applications
=====================================
.. note::
This state requires the Tomcat Manager webapp to be installed and running.
The following grains/pillars must be set for communication with Tomcat Manager
to work:
.. code-block:: yaml
tomcat-manager:
user: 'tomcat-manager'
passwd: 'Passw0rd'
Configuring Tomcat Manager
--------------------------
To manage webapps via the Tomcat Manager, you'll need to configure
a valid user in the file ``conf/tomcat-users.xml``.
.. code-block:: xml
:caption: conf/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat-manager" password="Passw0rd" roles="manager-script"/>
</tomcat-users>
Notes
-----
- Using multiple versions (aka. parallel deployments) on the same context
path is not supported.
- More information about the Tomcat Manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- If you use only this module for deployments you might want to restrict
access to the manager so it's only accessible via localhost.
For more info: http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Last tested on:
Tomcat Version:
Apache Tomcat/7.0.54
JVM Vendor:
Oracle Corporation
JVM Version:
1.8.0_101-b13
OS Architecture:
amd64
OS Name:
Linux
OS Version:
3.10.0-327.22.2.el7.x86_64
'''
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext import six
# Private
def __virtual__():
'''
Load if the module tomcat exists
'''
return 'tomcat' if 'tomcat.status' in __salt__ else False
# Functions
def war_deployed(name,
war,
force=False,
url='http://localhost:8080/manager',
timeout=180,
temp_war_location=None,
version=True):
'''
Enforce that the WAR will be deployed and started in the context path,
while making use of WAR versions in the filename.
.. note::
For more info about Tomcats file paths and context naming, please see
http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Naming
name
The context path to deploy (incl. forward slash) the WAR to.
war
Absolute path to WAR file (should be accessible by the user running
Tomcat) or a path supported by the ``salt.modules.cp.get_url`` function.
force : False
Force deployment even if the version strings are the same.
Disabled by default.
url : http://localhost:8080/manager
The URL of the Tomcat Web Application Manager.
timeout : 180
Timeout for HTTP requests to the Tomcat Manager.
temp_war_location : None
Use another location to temporarily copy the WAR file to.
By default the system's temp directory is used.
version : ''
Specify the WAR version. If this argument is provided, it overrides
the version encoded in the WAR file name, if one is present.
.. versionadded:: 2015.8.6
Use ``False`` or blank value to prevent guessing the version and keeping it blank.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
jenkins:
tomcat.war_deployed:
- name: /salt-powered-jenkins
- war: salt://jenkins-1.2.4.war
- require:
- service: application-service
.. note::
Be aware that in the above example the WAR ``jenkins-1.2.4.war`` will
be deployed to the context path ``salt-powered-jenkins##1.2.4``. To avoid this
either specify a version yourself, or set version to ``False``.
'''
# Prepare
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
# if version is defined or False, we don't want to overwrite
if version is True:
version = __salt__['tomcat.extract_war_version'](war) or ''
elif not version:
version = ''
webapps = __salt__['tomcat.ls'](url, timeout)
deploy = False
undeploy = False
status = True
# Gathered/specified new WAR version string
specified_ver = 'version {0}'.format(version) if version else 'no version'
# Determine what to do
try:
# Printed version strings, here to throw exception if no webapps[name]
current_ver = 'version ' + webapps[name]['version'] \
if webapps[name]['version'] else 'no version'
# `endswith` on the supposed string will cause Exception if empty
if (not webapps[name]['version'].endswith(version)
or (version == '' and webapps[name]['version'] != version)
or force):
deploy = True
undeploy = True
ret['changes']['undeploy'] = ('undeployed {0} with {1}'.
format(name, current_ver))
ret['changes']['deploy'] = ('will deploy {0} with {1}'.
format(name, specified_ver))
else:
deploy = False
ret['comment'] = ('{0} with {1} is already deployed'.
format(name, specified_ver))
if webapps[name]['mode'] != 'running':
ret['changes']['start'] = 'starting {0}'.format(name)
status = False
else:
return ret
except Exception:
deploy = True
ret['changes']['deploy'] = ('deployed {0} with {1}'.
format(name, specified_ver))
# Test
if __opts__['test']:
ret['result'] = None
return ret
# make sure the webapp is up if deployed
if deploy is False:
if status is False:
ret['comment'] = __salt__['tomcat.start'](name, url,
timeout=timeout)
ret['result'] = ret['comment'].startswith('OK')
return ret
# Undeploy
if undeploy:
un = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if un.startswith('FAIL'):
ret['result'] = False
ret['comment'] = un
return ret
# Deploy
deploy_res = __salt__['tomcat.deploy_war'](war,
name,
'yes',
url,
__env__,
timeout,
temp_war_location=temp_war_location,
version=version)
# Return
if deploy_res.startswith('OK'):
ret['result'] = True
ret['comment'] = six.text_type(__salt__['tomcat.ls'](url, timeout)[name])
ret['changes']['deploy'] = ('deployed {0} with {1}'.
format(name, specified_ver))
else:
ret['result'] = False
ret['comment'] = deploy_res
ret['changes'].pop('deploy')
return ret
def wait(name, url='http://localhost:8080/manager', timeout=180):
'''
Wait for the Tomcat Manager to load.
Notice that if tomcat is not running we won't wait for it start and the
state will fail. This state can be required in the tomcat.war_deployed
state to make sure tomcat is running and that the manager is running as
well and ready for deployment.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
tomcat-service:
service.running:
- name: tomcat
- enable: True
wait-for-tomcatmanager:
tomcat.wait:
- timeout: 300
- require:
- service: tomcat-service
jenkins:
tomcat.war_deployed:
- name: /ran
- war: salt://jenkins-1.2.4.war
- require:
- tomcat: wait-for-tomcatmanager
'''
result = __salt__['tomcat.status'](url, timeout)
ret = {'name': name,
'result': result,
'changes': {},
'comment': ('tomcat manager is ready' if result
else 'tomcat manager is not ready')
}
return ret
def undeployed(name,
url='http://localhost:8080/manager',
timeout=180):
'''
Enforce that the WAR will be undeployed from the server
name
The context path to undeploy.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
jenkins:
tomcat.undeployed:
- name: /ran
- require:
- service: application-service
'''
# Prepare
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not __salt__['tomcat.status'](url, timeout):
ret['comment'] = 'Tomcat Manager does not respond'
ret['result'] = False
return ret
try:
version = __salt__['tomcat.ls'](url, timeout)[name]['version']
ret['changes'] = {'undeploy': version}
except KeyError:
return ret
# Test
if __opts__['test']:
ret['result'] = None
return ret
undeploy = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if undeploy.startswith('FAIL'):
ret['result'] = False
ret['comment'] = undeploy
return ret
return ret
|
saltstack/salt
|
salt/states/tomcat.py
|
undeployed
|
python
|
def undeployed(name,
url='http://localhost:8080/manager',
timeout=180):
'''
Enforce that the WAR will be undeployed from the server
name
The context path to undeploy.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
jenkins:
tomcat.undeployed:
- name: /ran
- require:
- service: application-service
'''
# Prepare
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not __salt__['tomcat.status'](url, timeout):
ret['comment'] = 'Tomcat Manager does not respond'
ret['result'] = False
return ret
try:
version = __salt__['tomcat.ls'](url, timeout)[name]['version']
ret['changes'] = {'undeploy': version}
except KeyError:
return ret
# Test
if __opts__['test']:
ret['result'] = None
return ret
undeploy = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if undeploy.startswith('FAIL'):
ret['result'] = False
ret['comment'] = undeploy
return ret
return ret
|
Enforce that the WAR will be undeployed from the server
name
The context path to undeploy.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
jenkins:
tomcat.undeployed:
- name: /ran
- require:
- service: application-service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/tomcat.py#L297-L349
| null |
# -*- coding: utf-8 -*-
'''
Manage Apache Tomcat web applications
=====================================
.. note::
This state requires the Tomcat Manager webapp to be installed and running.
The following grains/pillars must be set for communication with Tomcat Manager
to work:
.. code-block:: yaml
tomcat-manager:
user: 'tomcat-manager'
passwd: 'Passw0rd'
Configuring Tomcat Manager
--------------------------
To manage webapps via the Tomcat Manager, you'll need to configure
a valid user in the file ``conf/tomcat-users.xml``.
.. code-block:: xml
:caption: conf/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat-manager" password="Passw0rd" roles="manager-script"/>
</tomcat-users>
Notes
-----
- Using multiple versions (aka. parallel deployments) on the same context
path is not supported.
- More information about the Tomcat Manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- If you use only this module for deployments you might want to restrict
access to the manager so it's only accessible via localhost.
For more info: http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Last tested on:
Tomcat Version:
Apache Tomcat/7.0.54
JVM Vendor:
Oracle Corporation
JVM Version:
1.8.0_101-b13
OS Architecture:
amd64
OS Name:
Linux
OS Version:
3.10.0-327.22.2.el7.x86_64
'''
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext import six
# Private
def __virtual__():
'''
Load if the module tomcat exists
'''
return 'tomcat' if 'tomcat.status' in __salt__ else False
# Functions
def war_deployed(name,
war,
force=False,
url='http://localhost:8080/manager',
timeout=180,
temp_war_location=None,
version=True):
'''
Enforce that the WAR will be deployed and started in the context path,
while making use of WAR versions in the filename.
.. note::
For more info about Tomcats file paths and context naming, please see
http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Naming
name
The context path to deploy (incl. forward slash) the WAR to.
war
Absolute path to WAR file (should be accessible by the user running
Tomcat) or a path supported by the ``salt.modules.cp.get_url`` function.
force : False
Force deployment even if the version strings are the same.
Disabled by default.
url : http://localhost:8080/manager
The URL of the Tomcat Web Application Manager.
timeout : 180
Timeout for HTTP requests to the Tomcat Manager.
temp_war_location : None
Use another location to temporarily copy the WAR file to.
By default the system's temp directory is used.
version : ''
Specify the WAR version. If this argument is provided, it overrides
the version encoded in the WAR file name, if one is present.
.. versionadded:: 2015.8.6
Use ``False`` or blank value to prevent guessing the version and keeping it blank.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
jenkins:
tomcat.war_deployed:
- name: /salt-powered-jenkins
- war: salt://jenkins-1.2.4.war
- require:
- service: application-service
.. note::
Be aware that in the above example the WAR ``jenkins-1.2.4.war`` will
be deployed to the context path ``salt-powered-jenkins##1.2.4``. To avoid this
either specify a version yourself, or set version to ``False``.
'''
# Prepare
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
# if version is defined or False, we don't want to overwrite
if version is True:
version = __salt__['tomcat.extract_war_version'](war) or ''
elif not version:
version = ''
webapps = __salt__['tomcat.ls'](url, timeout)
deploy = False
undeploy = False
status = True
# Gathered/specified new WAR version string
specified_ver = 'version {0}'.format(version) if version else 'no version'
# Determine what to do
try:
# Printed version strings, here to throw exception if no webapps[name]
current_ver = 'version ' + webapps[name]['version'] \
if webapps[name]['version'] else 'no version'
# `endswith` on the supposed string will cause Exception if empty
if (not webapps[name]['version'].endswith(version)
or (version == '' and webapps[name]['version'] != version)
or force):
deploy = True
undeploy = True
ret['changes']['undeploy'] = ('undeployed {0} with {1}'.
format(name, current_ver))
ret['changes']['deploy'] = ('will deploy {0} with {1}'.
format(name, specified_ver))
else:
deploy = False
ret['comment'] = ('{0} with {1} is already deployed'.
format(name, specified_ver))
if webapps[name]['mode'] != 'running':
ret['changes']['start'] = 'starting {0}'.format(name)
status = False
else:
return ret
except Exception:
deploy = True
ret['changes']['deploy'] = ('deployed {0} with {1}'.
format(name, specified_ver))
# Test
if __opts__['test']:
ret['result'] = None
return ret
# make sure the webapp is up if deployed
if deploy is False:
if status is False:
ret['comment'] = __salt__['tomcat.start'](name, url,
timeout=timeout)
ret['result'] = ret['comment'].startswith('OK')
return ret
# Undeploy
if undeploy:
un = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if un.startswith('FAIL'):
ret['result'] = False
ret['comment'] = un
return ret
# Deploy
deploy_res = __salt__['tomcat.deploy_war'](war,
name,
'yes',
url,
__env__,
timeout,
temp_war_location=temp_war_location,
version=version)
# Return
if deploy_res.startswith('OK'):
ret['result'] = True
ret['comment'] = six.text_type(__salt__['tomcat.ls'](url, timeout)[name])
ret['changes']['deploy'] = ('deployed {0} with {1}'.
format(name, specified_ver))
else:
ret['result'] = False
ret['comment'] = deploy_res
ret['changes'].pop('deploy')
return ret
def wait(name, url='http://localhost:8080/manager', timeout=180):
'''
Wait for the Tomcat Manager to load.
Notice that if tomcat is not running we won't wait for it start and the
state will fail. This state can be required in the tomcat.war_deployed
state to make sure tomcat is running and that the manager is running as
well and ready for deployment.
url : http://localhost:8080/manager
The URL of the server with the Tomcat Manager webapp.
timeout : 180
Timeout for HTTP request to the Tomcat Manager.
Example:
.. code-block:: yaml
tomcat-service:
service.running:
- name: tomcat
- enable: True
wait-for-tomcatmanager:
tomcat.wait:
- timeout: 300
- require:
- service: tomcat-service
jenkins:
tomcat.war_deployed:
- name: /ran
- war: salt://jenkins-1.2.4.war
- require:
- tomcat: wait-for-tomcatmanager
'''
result = __salt__['tomcat.status'](url, timeout)
ret = {'name': name,
'result': result,
'changes': {},
'comment': ('tomcat manager is ready' if result
else 'tomcat manager is not ready')
}
return ret
def mod_watch(name, url='http://localhost:8080/manager', timeout=180):
'''
The tomcat watcher, called to invoke the watch command.
When called, it will reload the webapp in question
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
msg = __salt__['tomcat.reload'](name, url, timeout)
result = msg.startswith('OK')
ret = {'name': name,
'result': result,
'changes': {name: result},
'comment': msg
}
return ret
|
saltstack/salt
|
salt/modules/xmpp.py
|
send_msg
|
python
|
def send_msg(recipient, message, jid=None, password=None, profile=None):
'''
Send a message to an XMPP recipient. Designed for use in states.
CLI Examples:
.. code-block:: bash
xmpp.send_msg 'admins@xmpp.example.com' 'This is a salt module test' \
profile='my-xmpp-account'
xmpp.send_msg 'admins@xmpp.example.com' 'This is a salt module test' \
jid='myuser@xmpp.example.com/salt' password='verybadpass'
'''
if profile:
creds = __salt__['config.option'](profile)
jid = creds.get('xmpp.jid')
password = creds.get('xmpp.password')
xmpp = SendMsgBot(jid, password, recipient, message)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0199') # XMPP Ping
if xmpp.connect():
xmpp.process(block=True)
return True
return False
|
Send a message to an XMPP recipient. Designed for use in states.
CLI Examples:
.. code-block:: bash
xmpp.send_msg 'admins@xmpp.example.com' 'This is a salt module test' \
profile='my-xmpp-account'
xmpp.send_msg 'admins@xmpp.example.com' 'This is a salt module test' \
jid='myuser@xmpp.example.com/salt' password='verybadpass'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xmpp.py#L121-L146
| null |
# -*- coding: utf-8 -*-
'''
Module for Sending Messages via XMPP (a.k.a. Jabber)
.. versionadded:: 2014.1.0
:depends: - sleekxmpp>=1.3.1
- pyasn1
- pyasn1-modules
- dnspython
:configuration: This module can be used by either passing a jid and password
directly to send_message, or by specifying the name of a configuration
profile in the minion config, minion pillar, or master config.
For example:
.. code-block:: yaml
my-xmpp-login:
xmpp.jid: myuser@jabber.example.org/resourcename
xmpp.password: verybadpass
The resourcename refers to the resource that is using this account. It is
user-definable, and optional. The following configurations are both valid:
.. code-block:: yaml
my-xmpp-login:
xmpp.jid: myuser@jabber.example.org/salt
xmpp.password: verybadpass
my-xmpp-login:
xmpp.jid: myuser@jabber.example.org
xmpp.password: verybadpass
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
HAS_LIBS = False
try:
from sleekxmpp import ClientXMPP as _ClientXMPP
from sleekxmpp.exceptions import XMPPError
HAS_LIBS = True
except ImportError:
class _ClientXMPP(object):
'''
Fake class in order not to raise errors
'''
log = logging.getLogger(__name__)
__virtualname__ = 'xmpp'
MUC_DEPRECATED = "Use of send mask waiters is deprecated."
def __virtual__():
'''
Only load this module if sleekxmpp is installed on this minion.
'''
if HAS_LIBS:
return __virtualname__
return (False, "Module xmpp: required libraries failed to load")
class SleekXMPPMUC(logging.Filter):
def filter(self, record):
return not record.getMessage() == MUC_DEPRECATED
class SendMsgBot(_ClientXMPP):
def __init__(self, jid, password, recipient, msg): # pylint: disable=E1002
# PyLint wrongly reports an error when calling super, hence the above
# disable call
super(SendMsgBot, self).__init__(jid, password)
self.recipients = [] if recipient is None else [recipient]
self.rooms = []
self.msg = msg
self.add_event_handler('session_start', self.start)
@classmethod
def create_multi(cls, jid, password, msg, recipients=None, rooms=None,
nick="SaltStack Bot"):
'''
Alternate constructor that accept multiple recipients and rooms
'''
obj = SendMsgBot(jid, password, None, msg)
obj.recipients = [] if recipients is None else recipients
obj.rooms = [] if rooms is None else rooms
obj.nick = nick
return obj
def start(self, event):
self.send_presence()
self.get_roster()
for recipient in self.recipients:
self.send_message(mto=recipient,
mbody=self.msg,
mtype='chat')
for room in self.rooms:
self.plugin['xep_0045'].joinMUC(room,
self.nick,
wait=True)
self.send_message(mto=room,
mbody=self.msg,
mtype='groupchat')
self.disconnect(wait=True)
def send_msg_multi(message,
recipients=None,
rooms=None,
jid=None,
password=None,
nick="SaltStack Bot",
profile=None):
'''
Send a message to an XMPP recipient, support send message to
multiple recipients or chat room.
CLI Examples:
.. code-block:: bash
xmpp.send_msg recipients=['admins@xmpp.example.com'] \
rooms=['secret@conference.xmpp.example.com'] \
'This is a salt module test' \
profile='my-xmpp-account'
xmpp.send_msg recipients=['admins@xmpp.example.com'] \
rooms=['secret@conference.xmpp.example.com'] \
'This is a salt module test' \
jid='myuser@xmpp.example.com/salt' password='verybadpass'
'''
# Remove: [WARNING ] Use of send mask waiters is deprecated.
for handler in logging.root.handlers:
handler.addFilter(SleekXMPPMUC())
if profile:
creds = __salt__['config.option'](profile)
jid = creds.get('xmpp.jid')
password = creds.get('xmpp.password')
xmpp = SendMsgBot.create_multi(
jid, password, message, recipients=recipients, rooms=rooms, nick=nick)
if rooms:
xmpp.register_plugin('xep_0045') # MUC plugin
if xmpp.connect():
try:
xmpp.process(block=True)
return True
except XMPPError as err:
log.error("Could not send message, error: %s", err)
else:
log.error("Could not connect to XMPP server")
return False
|
saltstack/salt
|
salt/modules/xmpp.py
|
send_msg_multi
|
python
|
def send_msg_multi(message,
recipients=None,
rooms=None,
jid=None,
password=None,
nick="SaltStack Bot",
profile=None):
'''
Send a message to an XMPP recipient, support send message to
multiple recipients or chat room.
CLI Examples:
.. code-block:: bash
xmpp.send_msg recipients=['admins@xmpp.example.com'] \
rooms=['secret@conference.xmpp.example.com'] \
'This is a salt module test' \
profile='my-xmpp-account'
xmpp.send_msg recipients=['admins@xmpp.example.com'] \
rooms=['secret@conference.xmpp.example.com'] \
'This is a salt module test' \
jid='myuser@xmpp.example.com/salt' password='verybadpass'
'''
# Remove: [WARNING ] Use of send mask waiters is deprecated.
for handler in logging.root.handlers:
handler.addFilter(SleekXMPPMUC())
if profile:
creds = __salt__['config.option'](profile)
jid = creds.get('xmpp.jid')
password = creds.get('xmpp.password')
xmpp = SendMsgBot.create_multi(
jid, password, message, recipients=recipients, rooms=rooms, nick=nick)
if rooms:
xmpp.register_plugin('xep_0045') # MUC plugin
if xmpp.connect():
try:
xmpp.process(block=True)
return True
except XMPPError as err:
log.error("Could not send message, error: %s", err)
else:
log.error("Could not connect to XMPP server")
return False
|
Send a message to an XMPP recipient, support send message to
multiple recipients or chat room.
CLI Examples:
.. code-block:: bash
xmpp.send_msg recipients=['admins@xmpp.example.com'] \
rooms=['secret@conference.xmpp.example.com'] \
'This is a salt module test' \
profile='my-xmpp-account'
xmpp.send_msg recipients=['admins@xmpp.example.com'] \
rooms=['secret@conference.xmpp.example.com'] \
'This is a salt module test' \
jid='myuser@xmpp.example.com/salt' password='verybadpass'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xmpp.py#L149-L197
|
[
"def create_multi(cls, jid, password, msg, recipients=None, rooms=None,\n nick=\"SaltStack Bot\"):\n '''\n Alternate constructor that accept multiple recipients and rooms\n '''\n obj = SendMsgBot(jid, password, None, msg)\n obj.recipients = [] if recipients is None else recipients\n obj.rooms = [] if rooms is None else rooms\n obj.nick = nick\n return obj\n"
] |
# -*- coding: utf-8 -*-
'''
Module for Sending Messages via XMPP (a.k.a. Jabber)
.. versionadded:: 2014.1.0
:depends: - sleekxmpp>=1.3.1
- pyasn1
- pyasn1-modules
- dnspython
:configuration: This module can be used by either passing a jid and password
directly to send_message, or by specifying the name of a configuration
profile in the minion config, minion pillar, or master config.
For example:
.. code-block:: yaml
my-xmpp-login:
xmpp.jid: myuser@jabber.example.org/resourcename
xmpp.password: verybadpass
The resourcename refers to the resource that is using this account. It is
user-definable, and optional. The following configurations are both valid:
.. code-block:: yaml
my-xmpp-login:
xmpp.jid: myuser@jabber.example.org/salt
xmpp.password: verybadpass
my-xmpp-login:
xmpp.jid: myuser@jabber.example.org
xmpp.password: verybadpass
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
HAS_LIBS = False
try:
from sleekxmpp import ClientXMPP as _ClientXMPP
from sleekxmpp.exceptions import XMPPError
HAS_LIBS = True
except ImportError:
class _ClientXMPP(object):
'''
Fake class in order not to raise errors
'''
log = logging.getLogger(__name__)
__virtualname__ = 'xmpp'
MUC_DEPRECATED = "Use of send mask waiters is deprecated."
def __virtual__():
'''
Only load this module if sleekxmpp is installed on this minion.
'''
if HAS_LIBS:
return __virtualname__
return (False, "Module xmpp: required libraries failed to load")
class SleekXMPPMUC(logging.Filter):
def filter(self, record):
return not record.getMessage() == MUC_DEPRECATED
class SendMsgBot(_ClientXMPP):
def __init__(self, jid, password, recipient, msg): # pylint: disable=E1002
# PyLint wrongly reports an error when calling super, hence the above
# disable call
super(SendMsgBot, self).__init__(jid, password)
self.recipients = [] if recipient is None else [recipient]
self.rooms = []
self.msg = msg
self.add_event_handler('session_start', self.start)
@classmethod
def create_multi(cls, jid, password, msg, recipients=None, rooms=None,
nick="SaltStack Bot"):
'''
Alternate constructor that accept multiple recipients and rooms
'''
obj = SendMsgBot(jid, password, None, msg)
obj.recipients = [] if recipients is None else recipients
obj.rooms = [] if rooms is None else rooms
obj.nick = nick
return obj
def start(self, event):
self.send_presence()
self.get_roster()
for recipient in self.recipients:
self.send_message(mto=recipient,
mbody=self.msg,
mtype='chat')
for room in self.rooms:
self.plugin['xep_0045'].joinMUC(room,
self.nick,
wait=True)
self.send_message(mto=room,
mbody=self.msg,
mtype='groupchat')
self.disconnect(wait=True)
def send_msg(recipient, message, jid=None, password=None, profile=None):
'''
Send a message to an XMPP recipient. Designed for use in states.
CLI Examples:
.. code-block:: bash
xmpp.send_msg 'admins@xmpp.example.com' 'This is a salt module test' \
profile='my-xmpp-account'
xmpp.send_msg 'admins@xmpp.example.com' 'This is a salt module test' \
jid='myuser@xmpp.example.com/salt' password='verybadpass'
'''
if profile:
creds = __salt__['config.option'](profile)
jid = creds.get('xmpp.jid')
password = creds.get('xmpp.password')
xmpp = SendMsgBot(jid, password, recipient, message)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0199') # XMPP Ping
if xmpp.connect():
xmpp.process(block=True)
return True
return False
|
saltstack/salt
|
salt/modules/xmpp.py
|
SendMsgBot.create_multi
|
python
|
def create_multi(cls, jid, password, msg, recipients=None, rooms=None,
nick="SaltStack Bot"):
'''
Alternate constructor that accept multiple recipients and rooms
'''
obj = SendMsgBot(jid, password, None, msg)
obj.recipients = [] if recipients is None else recipients
obj.rooms = [] if rooms is None else rooms
obj.nick = nick
return obj
|
Alternate constructor that accept multiple recipients and rooms
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xmpp.py#L90-L99
| null |
class SendMsgBot(_ClientXMPP):
def __init__(self, jid, password, recipient, msg): # pylint: disable=E1002
# PyLint wrongly reports an error when calling super, hence the above
# disable call
super(SendMsgBot, self).__init__(jid, password)
self.recipients = [] if recipient is None else [recipient]
self.rooms = []
self.msg = msg
self.add_event_handler('session_start', self.start)
@classmethod
def start(self, event):
self.send_presence()
self.get_roster()
for recipient in self.recipients:
self.send_message(mto=recipient,
mbody=self.msg,
mtype='chat')
for room in self.rooms:
self.plugin['xep_0045'].joinMUC(room,
self.nick,
wait=True)
self.send_message(mto=room,
mbody=self.msg,
mtype='groupchat')
self.disconnect(wait=True)
|
saltstack/salt
|
salt/beacons/twilio_txt_msg.py
|
beacon
|
python
|
def beacon(config):
'''
Emit a dict name "texts" whose value is a list
of texts.
.. code-block:: yaml
beacons:
twilio_txt_msg:
- account_sid: "<account sid>"
- auth_token: "<auth token>"
- twilio_number: "+15555555555"
- interval: 10
'''
log.trace('twilio_txt_msg beacon starting')
_config = {}
list(map(_config.update, config))
ret = []
if not all([_config['account_sid'],
_config['auth_token'],
_config['twilio_number']]):
return ret
output = {}
output['texts'] = []
client = TwilioRestClient(_config['account_sid'], _config['auth_token'])
messages = client.messages.list(to=_config['twilio_number'])
num_messages = len(messages)
log.trace('Num messages: %d', num_messages)
if not num_messages:
log.trace('Twilio beacon has no texts')
return ret
for message in messages:
item = {}
item['id'] = six.text_type(message.sid)
item['body'] = six.text_type(message.body)
item['from'] = six.text_type(message.from_)
item['sent'] = six.text_type(message.date_sent)
item['images'] = []
if int(message.num_media):
media = client.media(message.sid).list()
if media:
for pic in media:
item['images'].append(six.text_type(pic.uri))
output['texts'].append(item)
message.delete()
ret.append(output)
return ret
|
Emit a dict name "texts" whose value is a list
of texts.
.. code-block:: yaml
beacons:
twilio_txt_msg:
- account_sid: "<account sid>"
- auth_token: "<auth token>"
- twilio_number: "+15555555555"
- interval: 10
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/twilio_txt_msg.py#L60-L111
| null |
# -*- coding: utf-8 -*-
'''
Beacon to emit Twilio text messages
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
from salt.ext import six
from salt.ext.six.moves import map
# Import 3rd Party libs
try:
import twilio
# Grab version, ensure elements are ints
twilio_version = tuple([int(x) for x in twilio.__version_info__])
if twilio_version > (5, ):
from twilio.rest import Client as TwilioRestClient
else:
from twilio.rest import TwilioRestClient
HAS_TWILIO = True
except ImportError:
HAS_TWILIO = False
log = logging.getLogger(__name__)
__virtualname__ = 'twilio_txt_msg'
def __virtual__():
if HAS_TWILIO:
return __virtualname__
else:
return False
def validate(config):
'''
Validate the beacon configuration
'''
# Configuration for twilio_txt_msg beacon should be a list of dicts
if not isinstance(config, list):
return False, ('Configuration for twilio_txt_msg beacon '
'must be a list.')
else:
_config = {}
list(map(_config.update, config))
if not all(x in _config for x in ('account_sid',
'auth_token',
'twilio_number')):
return False, ('Configuration for twilio_txt_msg beacon '
'must contain account_sid, auth_token '
'and twilio_number items.')
return True, 'Valid beacon configuration'
|
saltstack/salt
|
salt/modules/boto_cloudwatch_event.py
|
exists
|
python
|
def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
events = conn.list_rules(NamePrefix=Name)
if not events:
return {'exists': False}
for rule in events.get('Rules', []):
if rule.get('Name', None) == Name:
return {'exists': True}
return {'exists': False}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
return {'error': err}
|
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudwatch_event.py#L89-L112
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon CloudWatch Events
.. versionadded:: 2016.11.0
:configuration: This module accepts explicit credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
cloudwatch_event.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudwatch_event.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cloudwatch_event.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError as e:
HAS_BOTO = False
# pylint: enable=import-error
from salt.ext import six
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'events')
def create_or_update(Name,
ScheduleExpression=None,
EventPattern=None,
Description=None,
RoleArn=None,
State=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an event rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.create_or_update my_rule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ScheduleExpression', 'EventPattern', 'State',
'Description', 'RoleArn'):
if locals()[arg] is not None:
kwargs[arg] = locals()[arg]
rule = conn.put_rule(Name=Name,
**kwargs)
if rule:
log.info('The newly created event rule is %s', rule.get('RuleArn'))
return {'created': True, 'arn': rule.get('RuleArn')}
else:
log.warning('Event rule was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.delete myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_rule(Name=Name)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def describe(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.describe myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.describe_rule(Name=Name)
if rule:
keys = ('Name', 'Arn', 'EventPattern',
'ScheduleExpression', 'State',
'Description',
'RoleArn')
return {'rule': dict([(k, rule.get(k)) for k in keys])}
else:
return {'rule': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def list_rules(region=None, key=None, keyid=None, profile=None):
'''
List, with details, all Cloudwatch Event rules visible in the current scope.
CLI example::
salt myminion boto_cloudwatch_event.list_rules region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = []
NextToken = ''
while NextToken is not None:
args = {'NextToken': NextToken} if NextToken else {}
r = conn.list_rules(**args)
ret += r.get('Rules', [])
NextToken = r.get('NextToken')
return ret
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_targets(Rule,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name list the targets of that rule.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.list_targets myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
targets = conn.list_targets_by_rule(Rule=Rule)
ret = []
if targets and 'Targets' in targets:
keys = ('Id', 'Arn', 'Input',
'InputPath')
for target in targets.get('Targets'):
ret.append(dict([(k, target.get(k)) for k in keys if k in target]))
return {'targets': ret}
else:
return {'targets': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def put_targets(Rule, Targets,
region=None, key=None, keyid=None, profile=None):
'''
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target1', 'Arn': 'arn:***'}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Targets, six.string_types):
Targets = salt.utils.json.loads(Targets)
failures = conn.put_targets(Rule=Rule, Targets=Targets)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries')}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def remove_targets(Rule, Ids,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name remove the named targets from the target list
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.remove_targets myrule ['Target1']
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Ids, six.string_types):
Ids = salt.utils.json.loads(Ids)
failures = conn.remove_targets(Rule=Rule, Ids=Ids)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries', 1)}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_cloudwatch_event.py
|
create_or_update
|
python
|
def create_or_update(Name,
ScheduleExpression=None,
EventPattern=None,
Description=None,
RoleArn=None,
State=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an event rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.create_or_update my_rule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ScheduleExpression', 'EventPattern', 'State',
'Description', 'RoleArn'):
if locals()[arg] is not None:
kwargs[arg] = locals()[arg]
rule = conn.put_rule(Name=Name,
**kwargs)
if rule:
log.info('The newly created event rule is %s', rule.get('RuleArn'))
return {'created': True, 'arn': rule.get('RuleArn')}
else:
log.warning('Event rule was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, create an event rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.create_or_update my_rule
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudwatch_event.py#L115-L153
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon CloudWatch Events
.. versionadded:: 2016.11.0
:configuration: This module accepts explicit credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
cloudwatch_event.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudwatch_event.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cloudwatch_event.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError as e:
HAS_BOTO = False
# pylint: enable=import-error
from salt.ext import six
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'events')
def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
events = conn.list_rules(NamePrefix=Name)
if not events:
return {'exists': False}
for rule in events.get('Rules', []):
if rule.get('Name', None) == Name:
return {'exists': True}
return {'exists': False}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
return {'error': err}
def delete(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.delete myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_rule(Name=Name)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def describe(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.describe myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.describe_rule(Name=Name)
if rule:
keys = ('Name', 'Arn', 'EventPattern',
'ScheduleExpression', 'State',
'Description',
'RoleArn')
return {'rule': dict([(k, rule.get(k)) for k in keys])}
else:
return {'rule': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def list_rules(region=None, key=None, keyid=None, profile=None):
'''
List, with details, all Cloudwatch Event rules visible in the current scope.
CLI example::
salt myminion boto_cloudwatch_event.list_rules region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = []
NextToken = ''
while NextToken is not None:
args = {'NextToken': NextToken} if NextToken else {}
r = conn.list_rules(**args)
ret += r.get('Rules', [])
NextToken = r.get('NextToken')
return ret
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_targets(Rule,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name list the targets of that rule.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.list_targets myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
targets = conn.list_targets_by_rule(Rule=Rule)
ret = []
if targets and 'Targets' in targets:
keys = ('Id', 'Arn', 'Input',
'InputPath')
for target in targets.get('Targets'):
ret.append(dict([(k, target.get(k)) for k in keys if k in target]))
return {'targets': ret}
else:
return {'targets': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def put_targets(Rule, Targets,
region=None, key=None, keyid=None, profile=None):
'''
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target1', 'Arn': 'arn:***'}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Targets, six.string_types):
Targets = salt.utils.json.loads(Targets)
failures = conn.put_targets(Rule=Rule, Targets=Targets)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries')}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def remove_targets(Rule, Ids,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name remove the named targets from the target list
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.remove_targets myrule ['Target1']
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Ids, six.string_types):
Ids = salt.utils.json.loads(Ids)
failures = conn.remove_targets(Rule=Rule, Ids=Ids)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries', 1)}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_cloudwatch_event.py
|
describe
|
python
|
def describe(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.describe myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.describe_rule(Name=Name)
if rule:
keys = ('Name', 'Arn', 'EventPattern',
'ScheduleExpression', 'State',
'Description',
'RoleArn')
return {'rule': dict([(k, rule.get(k)) for k in keys])}
else:
return {'rule': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
Given a rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.describe myrule
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudwatch_event.py#L180-L210
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon CloudWatch Events
.. versionadded:: 2016.11.0
:configuration: This module accepts explicit credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
cloudwatch_event.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudwatch_event.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cloudwatch_event.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError as e:
HAS_BOTO = False
# pylint: enable=import-error
from salt.ext import six
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'events')
def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
events = conn.list_rules(NamePrefix=Name)
if not events:
return {'exists': False}
for rule in events.get('Rules', []):
if rule.get('Name', None) == Name:
return {'exists': True}
return {'exists': False}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create_or_update(Name,
ScheduleExpression=None,
EventPattern=None,
Description=None,
RoleArn=None,
State=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an event rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.create_or_update my_rule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ScheduleExpression', 'EventPattern', 'State',
'Description', 'RoleArn'):
if locals()[arg] is not None:
kwargs[arg] = locals()[arg]
rule = conn.put_rule(Name=Name,
**kwargs)
if rule:
log.info('The newly created event rule is %s', rule.get('RuleArn'))
return {'created': True, 'arn': rule.get('RuleArn')}
else:
log.warning('Event rule was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.delete myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_rule(Name=Name)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def list_rules(region=None, key=None, keyid=None, profile=None):
'''
List, with details, all Cloudwatch Event rules visible in the current scope.
CLI example::
salt myminion boto_cloudwatch_event.list_rules region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = []
NextToken = ''
while NextToken is not None:
args = {'NextToken': NextToken} if NextToken else {}
r = conn.list_rules(**args)
ret += r.get('Rules', [])
NextToken = r.get('NextToken')
return ret
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_targets(Rule,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name list the targets of that rule.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.list_targets myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
targets = conn.list_targets_by_rule(Rule=Rule)
ret = []
if targets and 'Targets' in targets:
keys = ('Id', 'Arn', 'Input',
'InputPath')
for target in targets.get('Targets'):
ret.append(dict([(k, target.get(k)) for k in keys if k in target]))
return {'targets': ret}
else:
return {'targets': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def put_targets(Rule, Targets,
region=None, key=None, keyid=None, profile=None):
'''
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target1', 'Arn': 'arn:***'}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Targets, six.string_types):
Targets = salt.utils.json.loads(Targets)
failures = conn.put_targets(Rule=Rule, Targets=Targets)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries')}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def remove_targets(Rule, Ids,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name remove the named targets from the target list
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.remove_targets myrule ['Target1']
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Ids, six.string_types):
Ids = salt.utils.json.loads(Ids)
failures = conn.remove_targets(Rule=Rule, Ids=Ids)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries', 1)}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_cloudwatch_event.py
|
list_rules
|
python
|
def list_rules(region=None, key=None, keyid=None, profile=None):
'''
List, with details, all Cloudwatch Event rules visible in the current scope.
CLI example::
salt myminion boto_cloudwatch_event.list_rules region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = []
NextToken = ''
while NextToken is not None:
args = {'NextToken': NextToken} if NextToken else {}
r = conn.list_rules(**args)
ret += r.get('Rules', [])
NextToken = r.get('NextToken')
return ret
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
|
List, with details, all Cloudwatch Event rules visible in the current scope.
CLI example::
salt myminion boto_cloudwatch_event.list_rules region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudwatch_event.py#L213-L233
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon CloudWatch Events
.. versionadded:: 2016.11.0
:configuration: This module accepts explicit credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
cloudwatch_event.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudwatch_event.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cloudwatch_event.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError as e:
HAS_BOTO = False
# pylint: enable=import-error
from salt.ext import six
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'events')
def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
events = conn.list_rules(NamePrefix=Name)
if not events:
return {'exists': False}
for rule in events.get('Rules', []):
if rule.get('Name', None) == Name:
return {'exists': True}
return {'exists': False}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create_or_update(Name,
ScheduleExpression=None,
EventPattern=None,
Description=None,
RoleArn=None,
State=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an event rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.create_or_update my_rule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ScheduleExpression', 'EventPattern', 'State',
'Description', 'RoleArn'):
if locals()[arg] is not None:
kwargs[arg] = locals()[arg]
rule = conn.put_rule(Name=Name,
**kwargs)
if rule:
log.info('The newly created event rule is %s', rule.get('RuleArn'))
return {'created': True, 'arn': rule.get('RuleArn')}
else:
log.warning('Event rule was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.delete myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_rule(Name=Name)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def describe(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.describe myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.describe_rule(Name=Name)
if rule:
keys = ('Name', 'Arn', 'EventPattern',
'ScheduleExpression', 'State',
'Description',
'RoleArn')
return {'rule': dict([(k, rule.get(k)) for k in keys])}
else:
return {'rule': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def list_targets(Rule,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name list the targets of that rule.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.list_targets myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
targets = conn.list_targets_by_rule(Rule=Rule)
ret = []
if targets and 'Targets' in targets:
keys = ('Id', 'Arn', 'Input',
'InputPath')
for target in targets.get('Targets'):
ret.append(dict([(k, target.get(k)) for k in keys if k in target]))
return {'targets': ret}
else:
return {'targets': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def put_targets(Rule, Targets,
region=None, key=None, keyid=None, profile=None):
'''
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target1', 'Arn': 'arn:***'}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Targets, six.string_types):
Targets = salt.utils.json.loads(Targets)
failures = conn.put_targets(Rule=Rule, Targets=Targets)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries')}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def remove_targets(Rule, Ids,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name remove the named targets from the target list
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.remove_targets myrule ['Target1']
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Ids, six.string_types):
Ids = salt.utils.json.loads(Ids)
failures = conn.remove_targets(Rule=Rule, Ids=Ids)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries', 1)}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_cloudwatch_event.py
|
list_targets
|
python
|
def list_targets(Rule,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name list the targets of that rule.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.list_targets myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
targets = conn.list_targets_by_rule(Rule=Rule)
ret = []
if targets and 'Targets' in targets:
keys = ('Id', 'Arn', 'Input',
'InputPath')
for target in targets.get('Targets'):
ret.append(dict([(k, target.get(k)) for k in keys if k in target]))
return {'targets': ret}
else:
return {'targets': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
Given a rule name list the targets of that rule.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.list_targets myrule
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudwatch_event.py#L236-L266
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon CloudWatch Events
.. versionadded:: 2016.11.0
:configuration: This module accepts explicit credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
cloudwatch_event.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudwatch_event.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cloudwatch_event.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError as e:
HAS_BOTO = False
# pylint: enable=import-error
from salt.ext import six
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'events')
def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
events = conn.list_rules(NamePrefix=Name)
if not events:
return {'exists': False}
for rule in events.get('Rules', []):
if rule.get('Name', None) == Name:
return {'exists': True}
return {'exists': False}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create_or_update(Name,
ScheduleExpression=None,
EventPattern=None,
Description=None,
RoleArn=None,
State=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an event rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.create_or_update my_rule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ScheduleExpression', 'EventPattern', 'State',
'Description', 'RoleArn'):
if locals()[arg] is not None:
kwargs[arg] = locals()[arg]
rule = conn.put_rule(Name=Name,
**kwargs)
if rule:
log.info('The newly created event rule is %s', rule.get('RuleArn'))
return {'created': True, 'arn': rule.get('RuleArn')}
else:
log.warning('Event rule was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.delete myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_rule(Name=Name)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def describe(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.describe myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.describe_rule(Name=Name)
if rule:
keys = ('Name', 'Arn', 'EventPattern',
'ScheduleExpression', 'State',
'Description',
'RoleArn')
return {'rule': dict([(k, rule.get(k)) for k in keys])}
else:
return {'rule': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def list_rules(region=None, key=None, keyid=None, profile=None):
'''
List, with details, all Cloudwatch Event rules visible in the current scope.
CLI example::
salt myminion boto_cloudwatch_event.list_rules region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = []
NextToken = ''
while NextToken is not None:
args = {'NextToken': NextToken} if NextToken else {}
r = conn.list_rules(**args)
ret += r.get('Rules', [])
NextToken = r.get('NextToken')
return ret
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_targets(Rule, Targets,
region=None, key=None, keyid=None, profile=None):
'''
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target1', 'Arn': 'arn:***'}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Targets, six.string_types):
Targets = salt.utils.json.loads(Targets)
failures = conn.put_targets(Rule=Rule, Targets=Targets)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries')}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def remove_targets(Rule, Ids,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name remove the named targets from the target list
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.remove_targets myrule ['Target1']
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Ids, six.string_types):
Ids = salt.utils.json.loads(Ids)
failures = conn.remove_targets(Rule=Rule, Ids=Ids)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries', 1)}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_cloudwatch_event.py
|
put_targets
|
python
|
def put_targets(Rule, Targets,
region=None, key=None, keyid=None, profile=None):
'''
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target1', 'Arn': 'arn:***'}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Targets, six.string_types):
Targets = salt.utils.json.loads(Targets)
failures = conn.put_targets(Rule=Rule, Targets=Targets)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries')}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target1', 'Arn': 'arn:***'}]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudwatch_event.py#L269-L296
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon CloudWatch Events
.. versionadded:: 2016.11.0
:configuration: This module accepts explicit credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
cloudwatch_event.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudwatch_event.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cloudwatch_event.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError as e:
HAS_BOTO = False
# pylint: enable=import-error
from salt.ext import six
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'events')
def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
events = conn.list_rules(NamePrefix=Name)
if not events:
return {'exists': False}
for rule in events.get('Rules', []):
if rule.get('Name', None) == Name:
return {'exists': True}
return {'exists': False}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create_or_update(Name,
ScheduleExpression=None,
EventPattern=None,
Description=None,
RoleArn=None,
State=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an event rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.create_or_update my_rule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ScheduleExpression', 'EventPattern', 'State',
'Description', 'RoleArn'):
if locals()[arg] is not None:
kwargs[arg] = locals()[arg]
rule = conn.put_rule(Name=Name,
**kwargs)
if rule:
log.info('The newly created event rule is %s', rule.get('RuleArn'))
return {'created': True, 'arn': rule.get('RuleArn')}
else:
log.warning('Event rule was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.delete myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_rule(Name=Name)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def describe(Name,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.describe myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.describe_rule(Name=Name)
if rule:
keys = ('Name', 'Arn', 'EventPattern',
'ScheduleExpression', 'State',
'Description',
'RoleArn')
return {'rule': dict([(k, rule.get(k)) for k in keys])}
else:
return {'rule': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def list_rules(region=None, key=None, keyid=None, profile=None):
'''
List, with details, all Cloudwatch Event rules visible in the current scope.
CLI example::
salt myminion boto_cloudwatch_event.list_rules region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = []
NextToken = ''
while NextToken is not None:
args = {'NextToken': NextToken} if NextToken else {}
r = conn.list_rules(**args)
ret += r.get('Rules', [])
NextToken = r.get('NextToken')
return ret
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_targets(Rule,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name list the targets of that rule.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.list_targets myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
targets = conn.list_targets_by_rule(Rule=Rule)
ret = []
if targets and 'Targets' in targets:
keys = ('Id', 'Arn', 'Input',
'InputPath')
for target in targets.get('Targets'):
ret.append(dict([(k, target.get(k)) for k in keys if k in target]))
return {'targets': ret}
else:
return {'targets': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
def remove_targets(Rule, Ids,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name remove the named targets from the target list
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.remove_targets myrule ['Target1']
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Ids, six.string_types):
Ids = salt.utils.json.loads(Ids)
failures = conn.remove_targets(Rule=Rule, Ids=Ids)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries', 1)}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/smf_service.py
|
_get_enabled_disabled
|
python
|
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
|
DRY: Get all service FMRIs and their enabled property
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L38-L51
| null |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
available
|
python
|
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
|
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L98-L114
|
[
"def get_all():\n '''\n Return all installed services\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n ret = set()\n cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'\n lines = __salt__['cmd.run'](cmd).splitlines()\n for line in lines:\n comps = line.split()\n if not comps:\n continue\n ret.add(comps[0])\n return sorted(ret)\n"
] |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
missing
|
python
|
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
|
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L117-L131
|
[
"def get_all():\n '''\n Return all installed services\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n ret = set()\n cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'\n lines = __salt__['cmd.run'](cmd).splitlines()\n for line in lines:\n comps = line.split()\n if not comps:\n continue\n ret.add(comps[0])\n return sorted(ret)\n"
] |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
get_all
|
python
|
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
|
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L134-L152
| null |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
start
|
python
|
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
|
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L155-L176
| null |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
restart
|
python
|
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
|
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L193-L208
|
[
"def start(name):\n '''\n Start the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.start <service name>\n '''\n cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)\n retcode = __salt__['cmd.retcode'](cmd, python_shell=False)\n if not retcode:\n return True\n if retcode == 3:\n # Return code 3 means there was a problem with the service\n # A common case is being in the 'maintenance' state\n # Attempt a clear and try one more time\n clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)\n __salt__['cmd.retcode'](clear_cmd, python_shell=False)\n return not __salt__['cmd.retcode'](cmd, python_shell=False)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
reload_
|
python
|
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
|
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L211-L226
|
[
"def start(name):\n '''\n Start the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.start <service name>\n '''\n cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)\n retcode = __salt__['cmd.retcode'](cmd, python_shell=False)\n if not retcode:\n return True\n if retcode == 3:\n # Return code 3 means there was a problem with the service\n # A common case is being in the 'maintenance' state\n # Attempt a clear and try one more time\n clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)\n __salt__['cmd.retcode'](clear_cmd, python_shell=False)\n return not __salt__['cmd.retcode'](cmd, python_shell=False)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
status
|
python
|
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
|
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L229-L264
|
[
"def get_all():\n '''\n Return all installed services\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n ret = set()\n cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'\n lines = __salt__['cmd.run'](cmd).splitlines()\n for line in lines:\n comps = line.split()\n if not comps:\n continue\n ret.add(comps[0])\n return sorted(ret)\n"
] |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
enable
|
python
|
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
|
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L267-L278
| null |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
disable
|
python
|
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
|
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L281-L292
| null |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/smf_service.py
|
enabled
|
python
|
def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# The property that reveals whether a service is enabled
# can only be queried using the full FMRI
# We extract the FMRI and then do the query
fmri_cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
fmri = __salt__['cmd.run'](fmri_cmd, python_shell=False)
cmd = '/usr/sbin/svccfg -s {0} listprop general/enabled'.format(fmri)
comps = __salt__['cmd.run'](cmd, python_shell=False).split()
if comps[2] == 'true':
return True
else:
return False
|
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L295-L315
| null |
# -*- coding: utf-8 -*-
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
# Define the module's virtual name
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris' in __grains__['os_family']:
# Don't let this work on Solaris 9 since SMF doesn't exist on it.
if __grains__['kernelrelease'] == "5.9":
return (False, 'The smf execution module failed to load: SMF not available on Solaris 9.')
return __virtualname__
return (False, 'The smf execution module failed to load: only available on Solaris.')
def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if comps[2] == enabled_prop:
ret.add(comps[0].split("/:properties")[0])
return sorted(ret)
def get_running():
'''
Return the running services
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
cmd = '/usr/bin/svcs -H -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' in line:
ret.add(comps[0])
return sorted(ret)
def get_stopped():
'''
Return the stopped services
CLI Example:
.. code-block:: bash
salt '*' service.get_stopped
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
if 'online' not in line and 'legacy_run' not in line:
ret.add(comps[0])
return sorted(ret)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing net-snmp
'''
cmd = '/usr/bin/svcs -H -o FMRI {0}'.format(name)
name = __salt__['cmd.run'](cmd, python_shell=False)
return name not in get_all()
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
if not comps:
continue
ret.add(comps[0])
return sorted(ret)
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
if retcode == 3:
# Return code 3 means there was a problem with the service
# A common case is being in the 'maintenance' state
# Attempt a clear and try one more time
clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
__salt__['cmd.retcode'](clear_cmd, python_shell=False)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
return False
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
cmd = '/usr/sbin/svcadm disable -s -t {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = '/usr/bin/svcs -H -o STATE {0}'.format(service)
line = __salt__['cmd.run'](cmd, python_shell=False)
results[service] = line == 'online'
if contains_globbing:
return results
return results[name]
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
cmd = '/usr/sbin/svcadm enable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
cmd = '/usr/sbin/svcadm disable {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
return not enabled(name)
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("true")
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
# Note that this returns the full FMRI
return _get_enabled_disabled("false")
|
saltstack/salt
|
salt/modules/win_pkg.py
|
upgrade_available
|
python
|
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
|
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L187-L214
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def latest_version(*names, **kwargs):\n '''\n Return the latest version of the named package available for upgrade or\n installation. If more than one package name is specified, a dict of\n name/version pairs is returned.\n\n If the latest version of a given package is already installed, an empty\n string will be returned for that package.\n\n Args:\n names (str): A single or multiple names to lookup\n\n Kwargs:\n saltenv (str): Salt environment. Default ``base``\n refresh (bool): Refresh package metadata. Default ``True``\n\n Returns:\n dict: A dictionary of packages with the latest version available\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.latest_version <package name>\n salt '*' pkg.latest_version <package1> <package2> <package3> ...\n '''\n if not names:\n return ''\n\n # Initialize the return dict with empty strings\n ret = {}\n for name in names:\n ret[name] = ''\n\n saltenv = kwargs.get('saltenv', 'base')\n # Refresh before looking for the latest version available\n refresh = salt.utils.data.is_true(kwargs.get('refresh', True))\n\n # no need to call _refresh_db_conditional as list_pkgs will do it\n installed_pkgs = list_pkgs(\n versions_as_list=True, saltenv=saltenv, refresh=refresh)\n log.trace('List of installed packages: %s', installed_pkgs)\n\n # iterate over all requested package names\n for name in names:\n latest_installed = '0'\n\n # get latest installed version of package\n if name in installed_pkgs:\n log.trace('Determining latest installed version of %s', name)\n try:\n # installed_pkgs[name] Can be version number or 'Not Found'\n # 'Not Found' occurs when version number is not found in the registry\n latest_installed = sorted(\n installed_pkgs[name],\n key=cmp_to_key(_reverse_cmp_pkg_versions)\n ).pop()\n except IndexError:\n log.warning(\n '%s was empty in pkg.list_pkgs return data, this is '\n 'probably a bug in list_pkgs', name\n )\n else:\n log.debug('Latest installed version of %s is %s',\n name, latest_installed)\n\n # get latest available (from winrepo_dir) version of package\n pkg_info = _get_package_info(name, saltenv=saltenv)\n log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)\n\n # latest_available can be version number or 'latest' or even 'Not Found'\n latest_available = _get_latest_pkg_version(pkg_info)\n if latest_available:\n log.debug(\n 'Latest available version of package %s is %s',\n name, latest_available\n )\n\n # check, whether latest available version\n # is newer than latest installed version\n if compare_versions(ver1=six.text_type(latest_available),\n oper='>',\n ver2=six.text_type(latest_installed)):\n log.debug(\n 'Upgrade of %s from %s to %s is available',\n name, latest_installed, latest_available\n )\n ret[name] = latest_available\n else:\n log.debug(\n 'No newer version than %s of %s is available',\n latest_installed, name\n )\n if len(names) == 1:\n return ret[names[0]]\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
list_upgrades
|
python
|
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
|
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L217-L254
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def list_pkgs(versions_as_list=False,\n include_components=True,\n include_updates=True,\n **kwargs):\n '''\n List the packages currently installed.\n\n .. note::\n To view installed software as displayed in the Add/Remove Programs, set\n ``include_components`` and ``include_updates`` to False.\n\n Args:\n\n versions_as_list (bool):\n Returns the versions as a list\n\n include_components (bool):\n Include sub components of installed software. Default is ``True``\n\n include_updates (bool):\n Include software updates and Windows updates. Default is ``True``\n\n Kwargs:\n\n saltenv (str):\n The salt environment to use. Default ``base``\n\n refresh (bool):\n Refresh package metadata. Default ``False``\n\n Returns:\n dict: A dictionary of installed software with versions installed\n\n .. code-block:: cfg\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n saltenv = kwargs.get('saltenv', 'base')\n refresh = salt.utils.data.is_true(kwargs.get('refresh', False))\n _refresh_db_conditional(saltenv, force=refresh)\n\n ret = {}\n name_map = _get_name_map(saltenv)\n for pkg_name, val_list in six.iteritems(\n _get_reg_software(include_components=include_components,\n include_updates=include_updates)):\n if pkg_name in name_map:\n key = name_map[pkg_name]\n for val in val_list:\n if val == 'Not Found':\n # Look up version from winrepo\n pkg_info = _get_package_info(key, saltenv=saltenv)\n if not pkg_info:\n continue\n for pkg_ver in pkg_info.keys():\n if pkg_info[pkg_ver]['full_name'] == pkg_name:\n val = pkg_ver\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n else:\n key = pkg_name\n for val in val_list:\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def latest_version(*names, **kwargs):\n '''\n Return the latest version of the named package available for upgrade or\n installation. If more than one package name is specified, a dict of\n name/version pairs is returned.\n\n If the latest version of a given package is already installed, an empty\n string will be returned for that package.\n\n Args:\n names (str): A single or multiple names to lookup\n\n Kwargs:\n saltenv (str): Salt environment. Default ``base``\n refresh (bool): Refresh package metadata. Default ``True``\n\n Returns:\n dict: A dictionary of packages with the latest version available\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.latest_version <package name>\n salt '*' pkg.latest_version <package1> <package2> <package3> ...\n '''\n if not names:\n return ''\n\n # Initialize the return dict with empty strings\n ret = {}\n for name in names:\n ret[name] = ''\n\n saltenv = kwargs.get('saltenv', 'base')\n # Refresh before looking for the latest version available\n refresh = salt.utils.data.is_true(kwargs.get('refresh', True))\n\n # no need to call _refresh_db_conditional as list_pkgs will do it\n installed_pkgs = list_pkgs(\n versions_as_list=True, saltenv=saltenv, refresh=refresh)\n log.trace('List of installed packages: %s', installed_pkgs)\n\n # iterate over all requested package names\n for name in names:\n latest_installed = '0'\n\n # get latest installed version of package\n if name in installed_pkgs:\n log.trace('Determining latest installed version of %s', name)\n try:\n # installed_pkgs[name] Can be version number or 'Not Found'\n # 'Not Found' occurs when version number is not found in the registry\n latest_installed = sorted(\n installed_pkgs[name],\n key=cmp_to_key(_reverse_cmp_pkg_versions)\n ).pop()\n except IndexError:\n log.warning(\n '%s was empty in pkg.list_pkgs return data, this is '\n 'probably a bug in list_pkgs', name\n )\n else:\n log.debug('Latest installed version of %s is %s',\n name, latest_installed)\n\n # get latest available (from winrepo_dir) version of package\n pkg_info = _get_package_info(name, saltenv=saltenv)\n log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)\n\n # latest_available can be version number or 'latest' or even 'Not Found'\n latest_available = _get_latest_pkg_version(pkg_info)\n if latest_available:\n log.debug(\n 'Latest available version of package %s is %s',\n name, latest_available\n )\n\n # check, whether latest available version\n # is newer than latest installed version\n if compare_versions(ver1=six.text_type(latest_available),\n oper='>',\n ver2=six.text_type(latest_installed)):\n log.debug(\n 'Upgrade of %s from %s to %s is available',\n name, latest_installed, latest_available\n )\n ret[name] = latest_available\n else:\n log.debug(\n 'No newer version than %s of %s is available',\n latest_installed, name\n )\n if len(names) == 1:\n return ret[names[0]]\n return ret\n",
"def get_repo_data(saltenv='base'):\n '''\n Returns the existing package metadata db. Will create it, if it does not\n exist, however will not refresh it.\n\n Args:\n saltenv (str): Salt environment. Default ``base``\n\n Returns:\n dict: A dict containing contents of metadata db.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.get_repo_data\n '''\n # we only call refresh_db if it does not exist, as we want to return\n # the existing data even if its old, other parts of the code call this,\n # but they will call refresh if they need too.\n repo_details = _get_repo_details(saltenv)\n\n if repo_details.winrepo_age == -1:\n # no repo meta db\n log.debug('No winrepo.p cache file. Refresh pkg db now.')\n refresh_db(saltenv=saltenv)\n\n if 'winrepo.data' in __context__:\n log.trace('get_repo_data returning results from __context__')\n return __context__['winrepo.data']\n else:\n log.trace('get_repo_data called reading from disk')\n\n try:\n serial = salt.payload.Serial(__opts__)\n with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:\n try:\n repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})\n __context__['winrepo.data'] = repodata\n return repodata\n except Exception as exc:\n log.exception(exc)\n return {}\n except IOError as exc:\n log.error('Not able to read repo file')\n log.exception(exc)\n return {}\n",
"def _refresh_db_conditional(saltenv, **kwargs):\n '''\n Internal use only in this module, has a different set of defaults and\n returns True or False. And supports checking the age of the existing\n generated metadata db, as well as ensure metadata db exists to begin with\n\n Args:\n saltenv (str): Salt environment\n\n Kwargs:\n\n force (bool):\n Force a refresh if the minimum age has been reached. Default is\n False.\n\n failhard (bool):\n If ``True``, an error will be raised if any repo SLS files failed to\n process.\n\n Returns:\n bool: True Fetched or Cache uptodate, False to indicate an issue\n\n :codeauthor: Damon Atkins <https://github.com/damon-atkins>\n '''\n force = salt.utils.data.is_true(kwargs.pop('force', False))\n failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))\n expired_max = __opts__['winrepo_cache_expire_max']\n expired_min = __opts__['winrepo_cache_expire_min']\n\n repo_details = _get_repo_details(saltenv)\n\n # Skip force if age less than minimum age\n if force and expired_min > 0 and repo_details.winrepo_age < expired_min:\n log.info(\n 'Refresh skipped, age of winrepo metadata in seconds (%s) is less '\n 'than winrepo_cache_expire_min (%s)',\n repo_details.winrepo_age, expired_min\n )\n force = False\n\n # winrepo_age is -1 if repo db does not exist\n refresh = True if force \\\n or repo_details.winrepo_age == -1 \\\n or repo_details.winrepo_age > expired_max \\\n else False\n\n if not refresh:\n log.debug(\n 'Using existing pkg metadata db for saltenv \\'%s\\' (age is %s)',\n saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)\n )\n return True\n\n if repo_details.winrepo_age == -1:\n # no repo meta db\n log.debug(\n 'No winrepo.p cache file for saltenv \\'%s\\', creating one now',\n saltenv\n )\n\n results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)\n try:\n # Return True if there were no failed winrepo SLS files, and False if\n # failures were reported.\n return not bool(results.get('failed', 0))\n except AttributeError:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
list_available
|
python
|
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
|
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L257-L314
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def _get_package_info(name, saltenv='base'):\n '''\n Return package info. Returns empty map if package not available\n TODO: Add option for version\n '''\n return get_repo_data(saltenv).get('repo', {}).get(name, {})\n",
"def _refresh_db_conditional(saltenv, **kwargs):\n '''\n Internal use only in this module, has a different set of defaults and\n returns True or False. And supports checking the age of the existing\n generated metadata db, as well as ensure metadata db exists to begin with\n\n Args:\n saltenv (str): Salt environment\n\n Kwargs:\n\n force (bool):\n Force a refresh if the minimum age has been reached. Default is\n False.\n\n failhard (bool):\n If ``True``, an error will be raised if any repo SLS files failed to\n process.\n\n Returns:\n bool: True Fetched or Cache uptodate, False to indicate an issue\n\n :codeauthor: Damon Atkins <https://github.com/damon-atkins>\n '''\n force = salt.utils.data.is_true(kwargs.pop('force', False))\n failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))\n expired_max = __opts__['winrepo_cache_expire_max']\n expired_min = __opts__['winrepo_cache_expire_min']\n\n repo_details = _get_repo_details(saltenv)\n\n # Skip force if age less than minimum age\n if force and expired_min > 0 and repo_details.winrepo_age < expired_min:\n log.info(\n 'Refresh skipped, age of winrepo metadata in seconds (%s) is less '\n 'than winrepo_cache_expire_min (%s)',\n repo_details.winrepo_age, expired_min\n )\n force = False\n\n # winrepo_age is -1 if repo db does not exist\n refresh = True if force \\\n or repo_details.winrepo_age == -1 \\\n or repo_details.winrepo_age > expired_max \\\n else False\n\n if not refresh:\n log.debug(\n 'Using existing pkg metadata db for saltenv \\'%s\\' (age is %s)',\n saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)\n )\n return True\n\n if repo_details.winrepo_age == -1:\n # no repo meta db\n log.debug(\n 'No winrepo.p cache file for saltenv \\'%s\\', creating one now',\n saltenv\n )\n\n results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)\n try:\n # Return True if there were no failed winrepo SLS files, and False if\n # failures were reported.\n return not bool(results.get('failed', 0))\n except AttributeError:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
version
|
python
|
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
|
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L317-L364
|
[
"def list_pkgs(versions_as_list=False,\n include_components=True,\n include_updates=True,\n **kwargs):\n '''\n List the packages currently installed.\n\n .. note::\n To view installed software as displayed in the Add/Remove Programs, set\n ``include_components`` and ``include_updates`` to False.\n\n Args:\n\n versions_as_list (bool):\n Returns the versions as a list\n\n include_components (bool):\n Include sub components of installed software. Default is ``True``\n\n include_updates (bool):\n Include software updates and Windows updates. Default is ``True``\n\n Kwargs:\n\n saltenv (str):\n The salt environment to use. Default ``base``\n\n refresh (bool):\n Refresh package metadata. Default ``False``\n\n Returns:\n dict: A dictionary of installed software with versions installed\n\n .. code-block:: cfg\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n saltenv = kwargs.get('saltenv', 'base')\n refresh = salt.utils.data.is_true(kwargs.get('refresh', False))\n _refresh_db_conditional(saltenv, force=refresh)\n\n ret = {}\n name_map = _get_name_map(saltenv)\n for pkg_name, val_list in six.iteritems(\n _get_reg_software(include_components=include_components,\n include_updates=include_updates)):\n if pkg_name in name_map:\n key = name_map[pkg_name]\n for val in val_list:\n if val == 'Not Found':\n # Look up version from winrepo\n pkg_info = _get_package_info(key, saltenv=saltenv)\n if not pkg_info:\n continue\n for pkg_ver in pkg_info.keys():\n if pkg_info[pkg_ver]['full_name'] == pkg_name:\n val = pkg_ver\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n else:\n key = pkg_name\n for val in val_list:\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
list_pkgs
|
python
|
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
|
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L367-L445
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def _get_package_info(name, saltenv='base'):\n '''\n Return package info. Returns empty map if package not available\n TODO: Add option for version\n '''\n return get_repo_data(saltenv).get('repo', {}).get(name, {})\n",
"def _refresh_db_conditional(saltenv, **kwargs):\n '''\n Internal use only in this module, has a different set of defaults and\n returns True or False. And supports checking the age of the existing\n generated metadata db, as well as ensure metadata db exists to begin with\n\n Args:\n saltenv (str): Salt environment\n\n Kwargs:\n\n force (bool):\n Force a refresh if the minimum age has been reached. Default is\n False.\n\n failhard (bool):\n If ``True``, an error will be raised if any repo SLS files failed to\n process.\n\n Returns:\n bool: True Fetched or Cache uptodate, False to indicate an issue\n\n :codeauthor: Damon Atkins <https://github.com/damon-atkins>\n '''\n force = salt.utils.data.is_true(kwargs.pop('force', False))\n failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))\n expired_max = __opts__['winrepo_cache_expire_max']\n expired_min = __opts__['winrepo_cache_expire_min']\n\n repo_details = _get_repo_details(saltenv)\n\n # Skip force if age less than minimum age\n if force and expired_min > 0 and repo_details.winrepo_age < expired_min:\n log.info(\n 'Refresh skipped, age of winrepo metadata in seconds (%s) is less '\n 'than winrepo_cache_expire_min (%s)',\n repo_details.winrepo_age, expired_min\n )\n force = False\n\n # winrepo_age is -1 if repo db does not exist\n refresh = True if force \\\n or repo_details.winrepo_age == -1 \\\n or repo_details.winrepo_age > expired_max \\\n else False\n\n if not refresh:\n log.debug(\n 'Using existing pkg metadata db for saltenv \\'%s\\' (age is %s)',\n saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)\n )\n return True\n\n if repo_details.winrepo_age == -1:\n # no repo meta db\n log.debug(\n 'No winrepo.p cache file for saltenv \\'%s\\', creating one now',\n saltenv\n )\n\n results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)\n try:\n # Return True if there were no failed winrepo SLS files, and False if\n # failures were reported.\n return not bool(results.get('failed', 0))\n except AttributeError:\n return False\n",
"def _get_reg_software(include_components=True,\n include_updates=True):\n '''\n This searches the uninstall keys in the registry to find a match in the sub\n keys, it will return a dict with the display name as the key and the\n version as the value\n\n Args:\n\n include_components (bool):\n Include sub components of installed software. Default is ``True``\n\n include_updates (bool):\n Include software updates and Windows updates. Default is ``True``\n\n Returns:\n dict: A dictionary of installed software with versions installed\n\n .. code-block:: cfg\n\n {'<package_name>': '<version>'}\n '''\n # Logic for this can be found in this question:\n # https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry\n # and also in the collectPlatformDependentApplicationData function in\n # https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go\n reg_software = {}\n\n def skip_component(hive, key, sub_key, use_32bit):\n '''\n 'SystemComponent' must be either absent or present with a value of 0,\n because this value is usually set on programs that have been installed\n via a Windows Installer Package (MSI).\n\n Returns:\n bool: True if the package needs to be skipped, otherwise False\n '''\n if include_components:\n return False\n if __utils__['reg.value_exists'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='SystemComponent',\n use_32bit_registry=use_32bit):\n if __utils__['reg.read_value'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='SystemComponent',\n use_32bit_registry=use_32bit)['vdata'] > 0:\n return True\n return False\n\n def skip_win_installer(hive, key, sub_key, use_32bit):\n '''\n 'WindowsInstaller' must be either absent or present with a value of 0.\n If the value is set to 1, then the application is included in the list\n if and only if the corresponding compressed guid is also present in\n HKLM:\\\\Software\\\\Classes\\\\Installer\\\\Products\n\n Returns:\n bool: True if the package needs to be skipped, otherwise False\n '''\n products_key = 'Software\\\\Classes\\\\Installer\\\\Products\\\\{0}'\n if __utils__['reg.value_exists'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='WindowsInstaller',\n use_32bit_registry=use_32bit):\n if __utils__['reg.read_value'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='WindowsInstaller',\n use_32bit_registry=use_32bit)['vdata'] > 0:\n squid = salt.utils.win_functions.guid_to_squid(sub_key)\n if not __utils__['reg.key_exists'](\n hive='HKLM',\n key=products_key.format(squid),\n use_32bit_registry=use_32bit):\n return True\n return False\n\n def skip_uninstall_string(hive, key, sub_key, use_32bit):\n '''\n 'UninstallString' must be present, because it stores the command line\n that gets executed by Add/Remove programs, when the user tries to\n uninstall a program.\n\n Returns:\n bool: True if the package needs to be skipped, otherwise False\n '''\n if not __utils__['reg.value_exists'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='UninstallString',\n use_32bit_registry=use_32bit):\n return True\n return False\n\n def skip_release_type(hive, key, sub_key, use_32bit):\n '''\n 'ReleaseType' must either be absent or if present must not have a\n value set to 'Security Update', 'Update Rollup', or 'Hotfix', because\n that indicates it's an update to an existing program.\n\n Returns:\n bool: True if the package needs to be skipped, otherwise False\n '''\n if include_updates:\n return False\n skip_types = ['Hotfix',\n 'Security Update',\n 'Update Rollup']\n if __utils__['reg.value_exists'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='ReleaseType',\n use_32bit_registry=use_32bit):\n if __utils__['reg.read_value'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='ReleaseType',\n use_32bit_registry=use_32bit)['vdata'] in skip_types:\n return True\n return False\n\n def skip_parent_key(hive, key, sub_key, use_32bit):\n '''\n 'ParentKeyName' must NOT be present, because that indicates it's an\n update to the parent program.\n\n Returns:\n bool: True if the package needs to be skipped, otherwise False\n '''\n if __utils__['reg.value_exists'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='ParentKeyName',\n use_32bit_registry=use_32bit):\n return True\n\n return False\n\n def add_software(hive, key, sub_key, use_32bit):\n '''\n 'DisplayName' must be present with a valid value, as this is reflected\n as the software name returned by pkg.list_pkgs. Also, its value must\n not start with 'KB' followed by 6 numbers - as that indicates a\n Windows update.\n '''\n d_name_regdata = __utils__['reg.read_value'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='DisplayName',\n use_32bit_registry=use_32bit)\n\n if (not d_name_regdata['success'] or\n d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or\n d_name_regdata['vdata'] in ['(value not set)', None, False]):\n return\n d_name = d_name_regdata['vdata']\n\n if not include_updates:\n if re.match(r'^KB[0-9]{6}', d_name):\n return\n\n d_vers_regdata = __utils__['reg.read_value'](\n hive=hive,\n key='{0}\\\\{1}'.format(key, sub_key),\n vname='DisplayVersion',\n use_32bit_registry=use_32bit)\n\n d_vers = 'Not Found'\n if (d_vers_regdata['success'] and\n d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):\n if isinstance(d_vers_regdata['vdata'], int):\n d_vers = six.text_type(d_vers_regdata['vdata'])\n elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values\n d_vers = d_vers_regdata['vdata']\n\n reg_software.setdefault(d_name, []).append(d_vers)\n\n # Start gathering information from the registry\n # HKLM Uninstall 64 bit\n kwargs = {'hive': 'HKLM',\n 'key': 'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall',\n 'use_32bit': False}\n for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],\n key=kwargs['key']):\n kwargs['sub_key'] = sub_key\n if skip_component(**kwargs):\n continue\n if skip_win_installer(**kwargs):\n continue\n if skip_uninstall_string(**kwargs):\n continue\n if skip_release_type(**kwargs):\n continue\n if skip_parent_key(**kwargs):\n continue\n add_software(**kwargs)\n\n # HKLM Uninstall 32 bit\n kwargs['use_32bit'] = True\n for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],\n key=kwargs['key'],\n use_32bit_registry=kwargs['use_32bit']):\n kwargs['sub_key'] = sub_key\n if skip_component(**kwargs):\n continue\n if skip_win_installer(**kwargs):\n continue\n if skip_uninstall_string(**kwargs):\n continue\n if skip_release_type(**kwargs):\n continue\n if skip_parent_key(**kwargs):\n continue\n add_software(**kwargs)\n\n # HKLM Uninstall 64 bit\n kwargs = {'hive': 'HKLM',\n 'key': 'Software\\\\Classes\\\\Installer\\\\Products',\n 'use_32bit': False}\n userdata_key = 'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Installer\\\\' \\\n 'UserData\\\\S-1-5-18\\\\Products'\n for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):\n # If the key does not exist in userdata, skip it\n if not __utils__['reg.key_exists'](\n hive=kwargs['hive'],\n key='{0}\\\\{1}'.format(userdata_key, sub_key)):\n continue\n kwargs['sub_key'] = sub_key\n if skip_component(**kwargs):\n continue\n if skip_win_installer(**kwargs):\n continue\n add_software(**kwargs)\n\n # Uninstall for each user on the system (HKU), 64 bit\n # This has a propensity to take a while on a machine where many users have\n # logged in. Untested in such a scenario\n hive_hku = 'HKU'\n uninstall_key = '{0}\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall'\n product_key = '{0}\\\\Software\\\\Microsoft\\\\Installer\\\\Products'\n user_data_key = 'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Installer\\\\' \\\n 'UserData\\\\{0}\\\\Products\\\\{1}'\n for user_guid in __utils__['reg.list_keys'](hive=hive_hku):\n kwargs = {'hive': hive_hku,\n 'key': uninstall_key.format(user_guid),\n 'use_32bit': False}\n for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],\n key=kwargs['key']):\n kwargs['sub_key'] = sub_key\n if skip_component(**kwargs):\n continue\n if skip_win_installer(**kwargs):\n continue\n if skip_uninstall_string(**kwargs):\n continue\n if skip_release_type(**kwargs):\n continue\n if skip_parent_key(**kwargs):\n continue\n add_software(**kwargs)\n\n # While we have the user guid, we're gong to check userdata in HKLM\n for sub_key in __utils__['reg.list_keys'](hive=hive_hku,\n key=product_key.format(user_guid)):\n kwargs = {'hive': 'HKLM',\n 'key': user_data_key.format(user_guid, sub_key),\n 'sub_key': 'InstallProperties',\n 'use_32bit': False}\n if __utils__['reg.key_exists'](hive=kwargs['hive'],\n key=kwargs['key']):\n if skip_component(**kwargs):\n continue\n add_software(**kwargs)\n\n # Uninstall for each user on the system (HKU), 32 bit\n for user_guid in __utils__['reg.list_keys'](hive=hive_hku,\n use_32bit_registry=True):\n kwargs = {'hive': hive_hku,\n 'key': uninstall_key.format(user_guid),\n 'use_32bit': True}\n for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],\n key=kwargs['key'],\n use_32bit_registry=kwargs['use_32bit']):\n kwargs['sub_key'] = sub_key\n if skip_component(**kwargs):\n continue\n if skip_win_installer(**kwargs):\n continue\n if skip_uninstall_string(**kwargs):\n continue\n if skip_release_type(**kwargs):\n continue\n if skip_parent_key(**kwargs):\n continue\n add_software(**kwargs)\n\n # While we have the user guid, we're gong to check userdata in HKLM\n for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,\n key=product_key.format(user_guid),\n use_32bit_registry=True):\n kwargs = {'hive': 'HKLM',\n 'key': user_data_key.format(user_guid, sub_key_2),\n 'sub_key': 'InstallProperties',\n 'use_32bit': True}\n if __utils__['reg.key_exists'](hive=kwargs['hive'],\n key=kwargs['key'],\n use_32bit_registry=kwargs['use_32bit']):\n if skip_component(**kwargs):\n continue\n add_software(**kwargs)\n\n return reg_software\n",
"def _get_name_map(saltenv='base'):\n '''\n Return a reverse map of full pkg names to the names recognized by winrepo.\n '''\n u_name_map = {}\n name_map = get_repo_data(saltenv).get('name_map', {})\n\n if not six.PY2:\n return name_map\n\n for k in name_map:\n u_name_map[k] = name_map[k]\n return u_name_map\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
_get_reg_software
|
python
|
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
|
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L448-L763
| null |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
_refresh_db_conditional
|
python
|
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
|
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L766-L832
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def refresh_db(**kwargs):\n r'''\n Generates the local software metadata database (`winrepo.p`) on the minion.\n The database is stored in a serialized format located by default at the\n following location:\n\n ``C:\\salt\\var\\cache\\salt\\minion\\files\\base\\win\\repo-ng\\winrepo.p``\n\n This module performs the following steps to generate the software metadata\n database:\n\n - Fetch the package definition files (.sls) from `winrepo_source_dir`\n (default `salt://win/repo-ng`) and cache them in\n `<cachedir>\\files\\<saltenv>\\<winrepo_source_dir>`\n (default: ``C:\\salt\\var\\cache\\salt\\minion\\files\\base\\win\\repo-ng``)\n - Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the\n package definition files and generate the repository metadata database\n file (`winrepo.p`)\n - Return the report received from\n :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`\n\n The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All\n files that end with `.sls` in this and all subdirectories will be used to\n generate the repository metadata database (`winrepo.p`).\n\n .. note::\n - Hidden directories (directories beginning with '`.`', such as\n '`.git`') will be ignored.\n\n .. note::\n There is no need to call `pkg.refresh_db` every time you work with the\n pkg module. Automatic refresh will occur based on the following minion\n configuration settings:\n\n - `winrepo_cache_expire_min`\n - `winrepo_cache_expire_max`\n\n However, if the package definition files have changed, as would be the\n case if you are developing a new package definition, this function\n should be called to ensure the minion has the latest information about\n packages available to it.\n\n .. warning::\n Directories and files fetched from <winrepo_source_dir>\n (`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If\n two or more software definition files contain the same name, the last\n one processed replaces all data from the files processed before it.\n\n For more information see\n :ref:`Windows Software Repository <windows-package-manager>`\n\n Arguments:\n\n saltenv (str): Salt environment. Default: ``base``\n\n verbose (bool):\n Return a verbose data structure which includes 'success_list', a\n list of all sls files and the package names contained within.\n Default is 'False'\n\n failhard (bool):\n If ``True``, an error will be raised if any repo SLS files fails to\n process. If ``False``, no error will be raised, and a dictionary\n containing the full results will be returned.\n\n Returns:\n dict: A dictionary containing the results of the database refresh.\n\n .. note::\n A result with a `total: 0` generally means that the files are in the\n wrong location on the master. Try running the following command on the\n minion: `salt-call -l debug pkg.refresh saltenv=base`\n\n .. warning::\n When calling this command from a state using `module.run` be sure to\n pass `failhard: False`. Otherwise the state will report failure if it\n encounters a bad software definition file.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n salt '*' pkg.refresh_db saltenv=base\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n saltenv = kwargs.pop('saltenv', 'base')\n verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))\n failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))\n __context__.pop('winrepo.data', None)\n repo_details = _get_repo_details(saltenv)\n\n log.debug(\n 'Refreshing pkg metadata db for saltenv \\'%s\\' (age of existing '\n 'metadata is %s)',\n saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)\n )\n\n # Clear minion repo-ng cache see #35342 discussion\n log.info('Removing all *.sls files under \\'%s\\'', repo_details.local_dest)\n failed = []\n for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):\n for name in files:\n if name.endswith('.sls'):\n full_filename = os.path.join(root, name)\n try:\n os.remove(full_filename)\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n log.error('Failed to remove %s: %s', full_filename, exc)\n failed.append(full_filename)\n if failed:\n raise CommandExecutionError(\n 'Failed to clear one or more winrepo cache files',\n info={'failed': failed}\n )\n\n # Cache repo-ng locally\n log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)\n __salt__['cp.cache_dir'](\n path=repo_details.winrepo_source_dir,\n saltenv=saltenv,\n include_pat='*.sls',\n exclude_pat=r'E@\\/\\..*?\\/' # Exclude all hidden directories (.git)\n )\n return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)\n",
"def _get_repo_details(saltenv):\n '''\n Return repo details for the specified saltenv as a namedtuple\n '''\n contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)\n\n if contextkey in __context__:\n (winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]\n else:\n winrepo_source_dir = __opts__['winrepo_source_dir']\n dirs = [__opts__['cachedir'], 'files', saltenv]\n url_parts = _urlparse(winrepo_source_dir)\n dirs.append(url_parts.netloc)\n dirs.extend(url_parts.path.strip('/').split('/'))\n local_dest = os.sep.join(dirs)\n\n winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default\n # Check for a valid windows file name\n if not re.search(r'[\\/:*?\"<>|]',\n __opts__['winrepo_cachefile'],\n flags=re.IGNORECASE):\n winrepo_file = os.path.join(\n local_dest,\n __opts__['winrepo_cachefile']\n )\n else:\n log.error(\n 'minion configuration option \\'winrepo_cachefile\\' has been '\n 'ignored as its value (%s) is invalid. Please ensure this '\n 'option is set to a valid filename.',\n __opts__['winrepo_cachefile']\n )\n\n # Do some safety checks on the repo_path as its contents can be removed,\n # this includes check for bad coding\n system_root = os.environ.get('SystemRoot', r'C:\\Windows')\n if not salt.utils.path.safe_path(\n path=local_dest,\n allow_path='\\\\'.join([system_root, 'TEMP'])):\n\n raise CommandExecutionError(\n 'Attempting to delete files from a possibly unsafe location: '\n '{0}'.format(local_dest)\n )\n\n __context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)\n\n try:\n os.makedirs(local_dest)\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise CommandExecutionError(\n 'Failed to create {0}: {1}'.format(local_dest, exc)\n )\n\n winrepo_age = -1\n try:\n stat_result = os.stat(winrepo_file)\n mtime = stat_result.st_mtime\n winrepo_age = time.time() - mtime\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n raise CommandExecutionError(\n 'Failed to get age of {0}: {1}'.format(winrepo_file, exc)\n )\n except AttributeError:\n # Shouldn't happen but log if it does\n log.warning('st_mtime missing from stat result %s', stat_result)\n except TypeError:\n # Shouldn't happen but log if it does\n log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)\n\n repo_details = collections.namedtuple(\n 'RepoDetails',\n ('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')\n )\n return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
refresh_db
|
python
|
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
|
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L835-L961
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def clear_rtag(opts):\n '''\n Remove the rtag file\n '''\n try:\n os.remove(rtag(opts))\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n # Using __str__() here to get the fully-formatted error message\n # (error number, error message, path)\n log.warning('Encountered error removing rtag: %s', exc.__str__())\n",
"def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n",
"def _get_repo_details(saltenv):\n '''\n Return repo details for the specified saltenv as a namedtuple\n '''\n contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)\n\n if contextkey in __context__:\n (winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]\n else:\n winrepo_source_dir = __opts__['winrepo_source_dir']\n dirs = [__opts__['cachedir'], 'files', saltenv]\n url_parts = _urlparse(winrepo_source_dir)\n dirs.append(url_parts.netloc)\n dirs.extend(url_parts.path.strip('/').split('/'))\n local_dest = os.sep.join(dirs)\n\n winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default\n # Check for a valid windows file name\n if not re.search(r'[\\/:*?\"<>|]',\n __opts__['winrepo_cachefile'],\n flags=re.IGNORECASE):\n winrepo_file = os.path.join(\n local_dest,\n __opts__['winrepo_cachefile']\n )\n else:\n log.error(\n 'minion configuration option \\'winrepo_cachefile\\' has been '\n 'ignored as its value (%s) is invalid. Please ensure this '\n 'option is set to a valid filename.',\n __opts__['winrepo_cachefile']\n )\n\n # Do some safety checks on the repo_path as its contents can be removed,\n # this includes check for bad coding\n system_root = os.environ.get('SystemRoot', r'C:\\Windows')\n if not salt.utils.path.safe_path(\n path=local_dest,\n allow_path='\\\\'.join([system_root, 'TEMP'])):\n\n raise CommandExecutionError(\n 'Attempting to delete files from a possibly unsafe location: '\n '{0}'.format(local_dest)\n )\n\n __context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)\n\n try:\n os.makedirs(local_dest)\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise CommandExecutionError(\n 'Failed to create {0}: {1}'.format(local_dest, exc)\n )\n\n winrepo_age = -1\n try:\n stat_result = os.stat(winrepo_file)\n mtime = stat_result.st_mtime\n winrepo_age = time.time() - mtime\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n raise CommandExecutionError(\n 'Failed to get age of {0}: {1}'.format(winrepo_file, exc)\n )\n except AttributeError:\n # Shouldn't happen but log if it does\n log.warning('st_mtime missing from stat result %s', stat_result)\n except TypeError:\n # Shouldn't happen but log if it does\n log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)\n\n repo_details = collections.namedtuple(\n 'RepoDetails',\n ('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')\n )\n return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)\n",
"def genrepo(**kwargs):\n '''\n Generate package metadata db based on files within the winrepo_source_dir\n\n Kwargs:\n\n saltenv (str): Salt environment. Default: ``base``\n\n verbose (bool):\n Return verbose data structure which includes 'success_list', a list\n of all sls files and the package names contained within.\n Default ``False``.\n\n failhard (bool):\n If ``True``, an error will be raised if any repo SLS files failed\n to process. If ``False``, no error will be raised, and a dictionary\n containing the full results will be returned.\n\n .. note::\n - Hidden directories (directories beginning with '`.`', such as\n '`.git`') will be ignored.\n\n Returns:\n dict: A dictionary of the results of the command\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run pkg.genrepo\n salt -G 'os:windows' pkg.genrepo verbose=true failhard=false\n salt -G 'os:windows' pkg.genrepo saltenv=base\n '''\n saltenv = kwargs.pop('saltenv', 'base')\n verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))\n failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))\n\n ret = {}\n successful_verbose = {}\n total_files_processed = 0\n ret['repo'] = {}\n ret['errors'] = {}\n repo_details = _get_repo_details(saltenv)\n\n for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):\n\n # Skip hidden directories (.git)\n if re.search(r'[\\\\/]\\..*', root):\n log.debug('Skipping files in directory: %s', root)\n continue\n\n short_path = os.path.relpath(root, repo_details.local_dest)\n if short_path == '.':\n short_path = ''\n\n for name in files:\n if name.endswith('.sls'):\n total_files_processed += 1\n _repo_process_pkg_sls(\n os.path.join(root, name),\n os.path.join(short_path, name),\n ret,\n successful_verbose\n )\n serial = salt.payload.Serial(__opts__)\n\n with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:\n repo_cache.write(serial.dumps(ret))\n # For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues\n successful_count = len(successful_verbose)\n error_count = len(ret['errors'])\n if verbose:\n results = {\n 'total': total_files_processed,\n 'success': successful_count,\n 'failed': error_count,\n 'success_list': successful_verbose,\n 'failed_list': ret['errors']\n }\n else:\n if error_count > 0:\n results = {\n 'total': total_files_processed,\n 'success': successful_count,\n 'failed': error_count,\n 'failed_list': ret['errors']\n }\n else:\n results = {\n 'total': total_files_processed,\n 'success': successful_count,\n 'failed': error_count\n }\n\n if error_count > 0 and failhard:\n raise CommandExecutionError(\n 'Error occurred while generating repo db',\n info=results\n )\n else:\n return results\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
_get_repo_details
|
python
|
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
|
Return repo details for the specified saltenv as a namedtuple
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L964-L1040
|
[
"def safe_path(path, allow_path=None):\n r'''\n .. versionadded:: 2017.7.3\n\n Checks that the path is safe for modification by Salt. For example, you\n wouldn't want to have salt delete the contents of ``C:\\Windows``. The\n following directories are considered unsafe:\n\n - C:\\, D:\\, E:\\, etc.\n - \\\n - C:\\Windows\n\n Args:\n\n path (str): The path to check\n\n allow_paths (str, list): A directory or list of directories inside of\n path that may be safe. For example: ``C:\\Windows\\TEMP``\n\n Returns:\n bool: True if safe, otherwise False\n '''\n # Create regex definitions for directories that may be unsafe to modify\n system_root = os.environ.get('SystemRoot', 'C:\\\\Windows')\n deny_paths = (\n r'[a-z]\\:\\\\$', # C:\\, D:\\, etc\n r'\\\\$', # \\\n re.escape(system_root) # C:\\Windows\n )\n\n # Make allow_path a list\n if allow_path and not isinstance(allow_path, list):\n allow_path = [allow_path]\n\n # Create regex definition for directories we may want to make exceptions for\n allow_paths = list()\n if allow_path:\n for item in allow_path:\n allow_paths.append(re.escape(item))\n\n # Check the path to make sure it's not one of the bad paths\n good_path = True\n for d_path in deny_paths:\n if re.match(d_path, path, flags=re.IGNORECASE) is not None:\n # Found deny path\n good_path = False\n\n # If local_dest is one of the bad paths, check for exceptions\n if not good_path:\n for a_path in allow_paths:\n if re.match(a_path, path, flags=re.IGNORECASE) is not None:\n # Found exception\n good_path = True\n\n return good_path\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
genrepo
|
python
|
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
|
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L1043-L1143
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n",
"def _get_repo_details(saltenv):\n '''\n Return repo details for the specified saltenv as a namedtuple\n '''\n contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)\n\n if contextkey in __context__:\n (winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]\n else:\n winrepo_source_dir = __opts__['winrepo_source_dir']\n dirs = [__opts__['cachedir'], 'files', saltenv]\n url_parts = _urlparse(winrepo_source_dir)\n dirs.append(url_parts.netloc)\n dirs.extend(url_parts.path.strip('/').split('/'))\n local_dest = os.sep.join(dirs)\n\n winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default\n # Check for a valid windows file name\n if not re.search(r'[\\/:*?\"<>|]',\n __opts__['winrepo_cachefile'],\n flags=re.IGNORECASE):\n winrepo_file = os.path.join(\n local_dest,\n __opts__['winrepo_cachefile']\n )\n else:\n log.error(\n 'minion configuration option \\'winrepo_cachefile\\' has been '\n 'ignored as its value (%s) is invalid. Please ensure this '\n 'option is set to a valid filename.',\n __opts__['winrepo_cachefile']\n )\n\n # Do some safety checks on the repo_path as its contents can be removed,\n # this includes check for bad coding\n system_root = os.environ.get('SystemRoot', r'C:\\Windows')\n if not salt.utils.path.safe_path(\n path=local_dest,\n allow_path='\\\\'.join([system_root, 'TEMP'])):\n\n raise CommandExecutionError(\n 'Attempting to delete files from a possibly unsafe location: '\n '{0}'.format(local_dest)\n )\n\n __context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)\n\n try:\n os.makedirs(local_dest)\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise CommandExecutionError(\n 'Failed to create {0}: {1}'.format(local_dest, exc)\n )\n\n winrepo_age = -1\n try:\n stat_result = os.stat(winrepo_file)\n mtime = stat_result.st_mtime\n winrepo_age = time.time() - mtime\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n raise CommandExecutionError(\n 'Failed to get age of {0}: {1}'.format(winrepo_file, exc)\n )\n except AttributeError:\n # Shouldn't happen but log if it does\n log.warning('st_mtime missing from stat result %s', stat_result)\n except TypeError:\n # Shouldn't happen but log if it does\n log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)\n\n repo_details = collections.namedtuple(\n 'RepoDetails',\n ('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')\n )\n return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)\n",
"def dumps(self, msg, use_bin_type=False):\n '''\n Run the correct dumps serialization format\n\n :param use_bin_type: Useful for Python 3 support. Tells msgpack to\n differentiate between 'str' and 'bytes' types\n by encoding them differently.\n Since this changes the wire protocol, this\n option should not be used outside of IPC.\n '''\n def ext_type_encoder(obj):\n if isinstance(obj, six.integer_types):\n # msgpack can't handle the very long Python longs for jids\n # Convert any very long longs to strings\n return six.text_type(obj)\n elif isinstance(obj, (datetime.datetime, datetime.date)):\n # msgpack doesn't support datetime.datetime and datetime.date datatypes.\n # So here we have converted these types to custom datatype\n # This is msgpack Extended types numbered 78\n return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(\n obj.strftime('%Y%m%dT%H:%M:%S.%f')))\n # The same for immutable types\n elif isinstance(obj, immutabletypes.ImmutableDict):\n return dict(obj)\n elif isinstance(obj, immutabletypes.ImmutableList):\n return list(obj)\n elif isinstance(obj, (set, immutabletypes.ImmutableSet)):\n # msgpack can't handle set so translate it to tuple\n return tuple(obj)\n elif isinstance(obj, CaseInsensitiveDict):\n return dict(obj)\n # Nothing known exceptions found. Let msgpack raise it's own.\n return obj\n\n try:\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'use_bin_type' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n except (OverflowError, msgpack.exceptions.PackValueError):\n # msgpack<=0.4.6 don't call ext encoder on very long integers raising the error instead.\n # Convert any very long longs to strings and call dumps again.\n def verylong_encoder(obj, context):\n # Make sure we catch recursion here.\n objid = id(obj)\n if objid in context:\n return '<Recursion on {} with id={}>'.format(type(obj).__name__, id(obj))\n context.add(objid)\n\n if isinstance(obj, dict):\n for key, value in six.iteritems(obj.copy()):\n obj[key] = verylong_encoder(value, context)\n return dict(obj)\n elif isinstance(obj, (list, tuple)):\n obj = list(obj)\n for idx, entry in enumerate(obj):\n obj[idx] = verylong_encoder(entry, context)\n return obj\n # A value of an Integer object is limited from -(2^63) upto (2^64)-1 by MessagePack\n # spec. Here we care only of JIDs that are positive integers.\n if isinstance(obj, six.integer_types) and obj >= pow(2, 64):\n return six.text_type(obj)\n else:\n return obj\n\n msg = verylong_encoder(msg, set())\n if msgpack.version >= (0, 4, 0):\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
_get_source_sum
|
python
|
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
|
Extract the hash sum, whether it is in a remote hash file, or just a string.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L1218-L1252
| null |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
_get_msiexec
|
python
|
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
|
Return if msiexec.exe will be used and the command to invoke it.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L1255-L1271
| null |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
install
|
python
|
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
|
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L1274-L1723
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def list_pkgs(versions_as_list=False,\n include_components=True,\n include_updates=True,\n **kwargs):\n '''\n List the packages currently installed.\n\n .. note::\n To view installed software as displayed in the Add/Remove Programs, set\n ``include_components`` and ``include_updates`` to False.\n\n Args:\n\n versions_as_list (bool):\n Returns the versions as a list\n\n include_components (bool):\n Include sub components of installed software. Default is ``True``\n\n include_updates (bool):\n Include software updates and Windows updates. Default is ``True``\n\n Kwargs:\n\n saltenv (str):\n The salt environment to use. Default ``base``\n\n refresh (bool):\n Refresh package metadata. Default ``False``\n\n Returns:\n dict: A dictionary of installed software with versions installed\n\n .. code-block:: cfg\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n saltenv = kwargs.get('saltenv', 'base')\n refresh = salt.utils.data.is_true(kwargs.get('refresh', False))\n _refresh_db_conditional(saltenv, force=refresh)\n\n ret = {}\n name_map = _get_name_map(saltenv)\n for pkg_name, val_list in six.iteritems(\n _get_reg_software(include_components=include_components,\n include_updates=include_updates)):\n if pkg_name in name_map:\n key = name_map[pkg_name]\n for val in val_list:\n if val == 'Not Found':\n # Look up version from winrepo\n pkg_info = _get_package_info(key, saltenv=saltenv)\n if not pkg_info:\n continue\n for pkg_ver in pkg_info.keys():\n if pkg_info[pkg_ver]['full_name'] == pkg_name:\n val = pkg_ver\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n else:\n key = pkg_name\n for val in val_list:\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def _get_package_info(name, saltenv='base'):\n '''\n Return package info. Returns empty map if package not available\n TODO: Add option for version\n '''\n return get_repo_data(saltenv).get('repo', {}).get(name, {})\n",
"def _get_latest_pkg_version(pkginfo):\n '''\n Returns the latest version of the package.\n Will return 'latest' or version number string, and\n 'Not Found' if 'Not Found' is the only entry.\n '''\n if len(pkginfo) == 1:\n return next(six.iterkeys(pkginfo))\n try:\n return sorted(\n pkginfo,\n key=cmp_to_key(_reverse_cmp_pkg_versions)\n ).pop()\n except IndexError:\n return ''\n",
"def _get_source_sum(source_hash, file_path, saltenv):\n '''\n Extract the hash sum, whether it is in a remote hash file, or just a string.\n '''\n ret = dict()\n schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')\n invalid_hash_msg = (\"Source hash '{0}' format is invalid. It must be in \"\n \"the format <hash type>=<hash>\").format(source_hash)\n source_hash = six.text_type(source_hash)\n source_hash_scheme = _urlparse(source_hash).scheme\n\n if source_hash_scheme in schemes:\n # The source_hash is a file on a server\n cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)\n\n if not cached_hash_file:\n raise CommandExecutionError(('Source hash file {0} not'\n ' found').format(source_hash))\n\n ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)\n if ret is None:\n raise SaltInvocationError(invalid_hash_msg)\n else:\n # The source_hash is a hash string\n items = source_hash.split('=', 1)\n\n if len(items) != 2:\n invalid_hash_msg = ('{0}, or it must be a supported protocol'\n ': {1}').format(invalid_hash_msg,\n ', '.join(schemes))\n raise SaltInvocationError(invalid_hash_msg)\n\n ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]\n\n return ret\n",
"def _get_msiexec(use_msiexec):\n '''\n Return if msiexec.exe will be used and the command to invoke it.\n '''\n if use_msiexec is False:\n return False, ''\n if isinstance(use_msiexec, six.string_types):\n if os.path.isfile(use_msiexec):\n return True, use_msiexec\n else:\n log.warning(\n \"msiexec path '%s' not found. Using system registered \"\n \"msiexec instead\", use_msiexec\n )\n use_msiexec = True\n if use_msiexec is True:\n return True, 'msiexec'\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
upgrade
|
python
|
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
|
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L1726-L1754
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
saltstack/salt
|
salt/modules/win_pkg.py
|
remove
|
python
|
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
# no need to call _refresh_db_conditional as list_pkgs will do it
ret = {}
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Get package parameters
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = [] # list of changed package names
for pkgname, version_num in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkgname, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
msg = 'Unable to locate package {0}'.format(pkgname)
log.error(msg)
ret[pkgname] = msg
continue
# Check to see if package is installed on the system
if pkgname not in old:
log.debug('%s %s not installed', pkgname, version_num if version_num else '')
ret[pkgname] = {'current': 'not installed'}
continue
removal_targets = []
# Only support a single version number
if version_num is not None:
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
version_num = six.text_type(version_num)
# At least one version of the software is installed.
if version_num is None:
for ver_install in old[pkgname]:
if ver_install not in pkginfo and 'latest' in pkginfo:
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
else:
removal_targets.append(ver_install)
else:
if version_num in pkginfo:
# we known how to remove this version
if version_num in old[pkgname]:
removal_targets.append(version_num)
else:
log.debug('%s %s not installed', pkgname, version_num)
ret[pkgname] = {'current': '{0} not installed'.format(version_num)}
continue
elif 'latest' in pkginfo:
# we do not have version entry, assume software can self upgrade and use latest
log.debug('%s %s using package latest entry to to remove', pkgname, version_num)
removal_targets.append('latest')
if not removal_targets:
log.error('%s %s no definition to remove this version', pkgname, version_num)
ret[pkgname] = {
'current': '{0} no definition, cannot removed'.format(version_num)
}
continue
for target in removal_targets:
# Get the uninstaller
uninstaller = pkginfo[target].get('uninstaller', '')
cache_dir = pkginfo[target].get('cache_dir', False)
uninstall_flags = pkginfo[target].get('uninstall_flags', '')
# If no uninstaller found, use the installer with uninstall flags
if not uninstaller and uninstall_flags:
uninstaller = pkginfo[target].get('installer', '')
# If still no uninstaller found, fail
if not uninstaller:
log.error(
'No installer or uninstaller configured for package %s',
pkgname,
)
ret[pkgname] = {'no uninstaller defined': target}
continue
# Where is the uninstaller
if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and uninstaller.startswith('salt:'):
path, _ = os.path.split(uninstaller)
__salt__['cp.cache_dir'](path,
saltenv,
False,
None,
'E@init.sls$')
# Check to see if the uninstaller is cached
cached_pkg = __salt__['cp.is_cached'](uninstaller, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](uninstaller, saltenv)
# Check if the uninstaller was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
# Compare the hash of the cached installer to the source only if
# the file is hosted on salt:
# TODO cp.cache_file does cache and hash checking? So why do it again?
if uninstaller.startswith('salt:'):
if __salt__['cp.hash_file'](uninstaller, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](
uninstaller, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, uninstaller)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
# Run the uninstaller directly
# (not hosted on salt:, https:, etc.)
cached_pkg = os.path.expandvars(uninstaller)
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path, _ = os.path.split(cached_pkg)
# os.path.expandvars is not required as we run everything through cmd.exe /s /c
if kwargs.get('extra_uninstall_flags'):
uninstall_flags = '{0} {1}'.format(
uninstall_flags, kwargs.get('extra_uninstall_flags', ''))
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[target].get('msiexec', False))
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
if use_msiexec:
# Check if uninstaller is set to {guid}, if not we assume its a remote msi file.
# which has already been downloaded.
arguments = '"{0}" /X "{1}"'.format(msiexec, cached_pkg)
else:
arguments = '"{0}"'.format(cached_pkg)
if uninstall_flags:
arguments = '{0} {1}'.format(arguments, uninstall_flags)
# Uninstall the software
changed.append(pkgname)
# Check Use Scheduler Option
if pkginfo[target].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to remove %s', pkgname)
log.error('Scheduled Task failed to run')
ret[pkgname] = {'uninstall status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all'](
'"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkgname] = {'uninstall status': 'success'}
changed.append(pkgname)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkgname] = {'uninstall status': 'success, reboot required'}
changed.append(pkgname)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkgname] = {'uninstall status': 'success, reboot initiated'}
changed.append(pkgname)
else:
log.error('Failed to remove %s', pkgname)
log.error('retcode %s', result['retcode'])
log.error('uninstaller output: %s', result['stdout'])
ret[pkgname] = {'uninstall status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
end_t = time.time() + 3 # give it 3 seconds to catch up.
while not found_chgs and time.time() < end_t:
time.sleep(0.5)
new = list_pkgs(saltenv=saltenv, refresh=False)
difference = salt.utils.data.compare_dicts(old, new)
found_chgs = all(name in difference for name in changed)
if not found_chgs:
log.warning('Expected changes for package removal may not have occured')
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
|
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Kwargs:
version (str):
The version of the package to be uninstalled. If this option is
used to to uninstall multiple packages, then this version will be
applied to all targeted packages. Recommended using only when
uninstalling a single package. If this parameter is omitted, the
latest version will be uninstalled.
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: Returns a dict containing the changes.
If the package is removed by ``pkg.remove``:
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If the package is already uninstalled:
{'<package>': {'current': 'not installed'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pkg.py#L1757-L2044
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def list_pkgs(versions_as_list=False,\n include_components=True,\n include_updates=True,\n **kwargs):\n '''\n List the packages currently installed.\n\n .. note::\n To view installed software as displayed in the Add/Remove Programs, set\n ``include_components`` and ``include_updates`` to False.\n\n Args:\n\n versions_as_list (bool):\n Returns the versions as a list\n\n include_components (bool):\n Include sub components of installed software. Default is ``True``\n\n include_updates (bool):\n Include software updates and Windows updates. Default is ``True``\n\n Kwargs:\n\n saltenv (str):\n The salt environment to use. Default ``base``\n\n refresh (bool):\n Refresh package metadata. Default ``False``\n\n Returns:\n dict: A dictionary of installed software with versions installed\n\n .. code-block:: cfg\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n saltenv = kwargs.get('saltenv', 'base')\n refresh = salt.utils.data.is_true(kwargs.get('refresh', False))\n _refresh_db_conditional(saltenv, force=refresh)\n\n ret = {}\n name_map = _get_name_map(saltenv)\n for pkg_name, val_list in six.iteritems(\n _get_reg_software(include_components=include_components,\n include_updates=include_updates)):\n if pkg_name in name_map:\n key = name_map[pkg_name]\n for val in val_list:\n if val == 'Not Found':\n # Look up version from winrepo\n pkg_info = _get_package_info(key, saltenv=saltenv)\n if not pkg_info:\n continue\n for pkg_ver in pkg_info.keys():\n if pkg_info[pkg_ver]['full_name'] == pkg_name:\n val = pkg_ver\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n else:\n key = pkg_name\n for val in val_list:\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def _get_package_info(name, saltenv='base'):\n '''\n Return package info. Returns empty map if package not available\n TODO: Add option for version\n '''\n return get_repo_data(saltenv).get('repo', {}).get(name, {})\n",
"def _get_msiexec(use_msiexec):\n '''\n Return if msiexec.exe will be used and the command to invoke it.\n '''\n if use_msiexec is False:\n return False, ''\n if isinstance(use_msiexec, six.string_types):\n if os.path.isfile(use_msiexec):\n return True, use_msiexec\n else:\n log.warning(\n \"msiexec path '%s' not found. Using system registered \"\n \"msiexec instead\", use_msiexec\n )\n use_msiexec = True\n if use_msiexec is True:\n return True, 'msiexec'\n"
] |
# -*- coding: utf-8 -*-
'''
A module to manage software on Windows
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
The following functions require the existence of a :ref:`windows repository
<windows-package-manager>` metadata DB, typically created by running
:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:
- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`
- :py:func:`pkg.install <salt.modules.win_pkg.install>`
- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`
- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`
- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`
- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`
- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`
If a metadata DB does not already exist and one of these functions is run, then
one will be created from the repo SLS files that are present.
As the creation of this metadata can take some time, the
:conf_minion:`winrepo_cache_expire_min` minion config option can be used to
suppress refreshes when the metadata is less than a given number of seconds
old.
.. note::
Version numbers can be ``version number string``, ``latest`` and ``Not
Found``, where ``Not Found`` means this module was not able to determine
the version of the software installed, it can also be used as the version
number in sls definitions file in these cases. Versions numbers are sorted
in order of 0, ``Not Found``, ``order version numbers``, ..., ``latest``.
'''
# Import python future libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
import logging
import os
import re
import time
import sys
from functools import cmp_to_key
# Import third party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# Import salt libs
from salt.exceptions import (CommandExecutionError,
SaltInvocationError,
SaltRenderError)
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.pkg
import salt.utils.platform
import salt.utils.versions
import salt.utils.win_functions
import salt.syspaths
import salt.payload
from salt.exceptions import MinionError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_pkg: module only works on Windows systems")
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
Args:
names (str): A single or multiple names to lookup
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``True``
Returns:
dict: A dictionary of packages with the latest version available
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if not names:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
latest_installed = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Determining latest installed version of %s', name)
try:
# installed_pkgs[name] Can be version number or 'Not Found'
# 'Not Found' occurs when version number is not found in the registry
latest_installed = sorted(
installed_pkgs[name],
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
log.warning(
'%s was empty in pkg.list_pkgs return data, this is '
'probably a bug in list_pkgs', name
)
else:
log.debug('Latest installed version of %s is %s',
name, latest_installed)
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
Args:
name (str): The name of a single package
Kwargs:
refresh (bool): Refresh package metadata. Default ``True``
saltenv (str): The salt environment. Default ``base``
Returns:
bool: True if new version available, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
saltenv = kwargs.get('saltenv', 'base')
# Refresh before looking for the latest version available,
# same default as latest_version
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
# if latest_version returns blank, the latest version is already installed or
# their is no package definition. This is a salt standard which could be improved.
return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
Args:
refresh (bool): Refresh package metadata. Default ``True``
Kwargs:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dictionary of packages with available upgrades
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
_refresh_db_conditional(saltenv, force=refresh)
installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv)
available_pkgs = get_repo_data(saltenv).get('repo')
pkgs = {}
for pkg in installed_pkgs:
if pkg in available_pkgs:
# latest_version() will be blank if the latest version is installed.
# or the package name is wrong. Given we check available_pkgs, this
# should not be the case of wrong package name.
# Note: latest_version() is an expensive way to do this as it
# calls list_pkgs each time.
latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv)
if latest_ver:
pkgs[pkg] = latest_ver
return pkgs
def list_available(*names, **kwargs):
'''
Return a list of available versions of the specified package.
Args:
names (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
return_dict_always (bool):
Default ``False`` dict when a single package name is queried.
Returns:
dict: The package name with its available versions
.. code-block:: cfg
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name> return_dict_always=True
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
return_dict_always = \
salt.utils.data.is_true(kwargs.get('return_dict_always', False))
if len(names) == 1 and not return_dict_always:
pkginfo = _get_package_info(names[0], saltenv=saltenv)
if not pkginfo:
return ''
versions = sorted(
list(pkginfo.keys()),
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name, saltenv=saltenv)
if not pkginfo:
continue
verlist = sorted(
list(pkginfo.keys()) if pkginfo else [],
key=cmp_to_key(_reverse_cmp_pkg_versions)
)
versions[name] = verlist
return versions
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
Args:
name (str): One or more package names
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``False``.
Returns:
str: version string when a single package is specified.
dict: The package name(s) with the installed versions.
.. code-block:: cfg
{['<version>', '<version>', ]} OR
{'<package name>': ['<version>', '<version>', ]}
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package name01> <package name02>
'''
# Standard is return empty string even if not a valid name
# TODO: Look at returning an error across all platforms with
# CommandExecutionError(msg,info={'errors': errors })
# available_pkgs = get_repo_data(saltenv).get('repo')
# for name in names:
# if name in available_pkgs:
# ret[name] = installed_pkgs.get(name, '')
saltenv = kwargs.get('saltenv', 'base')
installed_pkgs = list_pkgs(saltenv=saltenv, refresh=kwargs.get('refresh', False))
if len(names) == 1:
return installed_pkgs.get(names[0], '')
ret = {}
for name in names:
ret[name] = installed_pkgs.get(name, '')
return ret
def list_pkgs(versions_as_list=False,
include_components=True,
include_updates=True,
**kwargs):
'''
List the packages currently installed.
.. note::
To view installed software as displayed in the Add/Remove Programs, set
``include_components`` and ``include_updates`` to False.
Args:
versions_as_list (bool):
Returns the versions as a list
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Kwargs:
saltenv (str):
The salt environment to use. Default ``base``
refresh (bool):
Refresh package metadata. Default ``False``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
saltenv = kwargs.get('saltenv', 'base')
refresh = salt.utils.data.is_true(kwargs.get('refresh', False))
_refresh_db_conditional(saltenv, force=refresh)
ret = {}
name_map = _get_name_map(saltenv)
for pkg_name, val_list in six.iteritems(
_get_reg_software(include_components=include_components,
include_updates=include_updates)):
if pkg_name in name_map:
key = name_map[pkg_name]
for val in val_list:
if val == 'Not Found':
# Look up version from winrepo
pkg_info = _get_package_info(key, saltenv=saltenv)
if not pkg_info:
continue
for pkg_ver in pkg_info.keys():
if pkg_info[pkg_ver]['full_name'] == pkg_name:
val = pkg_ver
__salt__['pkg_resource.add_pkg'](ret, key, val)
else:
key = pkg_name
for val in val_list:
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_updates (bool):
Include software updates and Windows updates. Default is ``True``
Returns:
dict: A dictionary of installed software with versions installed
.. code-block:: cfg
{'<package_name>': '<version>'}
'''
# Logic for this can be found in this question:
# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry
# and also in the collectPlatformDependentApplicationData function in
# https://github.com/aws/amazon-ssm-agent/blob/master/agent/plugins/inventory/gatherers/application/dataProvider_windows.go
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
'''
'SystemComponent' must be either absent or present with a value of 0,
because this value is usually set on programs that have been installed
via a Windows Installer Package (MSI).
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_components:
return False
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='SystemComponent',
use_32bit_registry=use_32bit)['vdata'] > 0:
return True
return False
def skip_win_installer(hive, key, sub_key, use_32bit):
'''
'WindowsInstaller' must be either absent or present with a value of 0.
If the value is set to 1, then the application is included in the list
if and only if the corresponding compressed guid is also present in
HKLM:\\Software\\Classes\\Installer\\Products
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
products_key = 'Software\\Classes\\Installer\\Products\\{0}'
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='WindowsInstaller',
use_32bit_registry=use_32bit)['vdata'] > 0:
squid = salt.utils.win_functions.guid_to_squid(sub_key)
if not __utils__['reg.key_exists'](
hive='HKLM',
key=products_key.format(squid),
use_32bit_registry=use_32bit):
return True
return False
def skip_uninstall_string(hive, key, sub_key, use_32bit):
'''
'UninstallString' must be present, because it stores the command line
that gets executed by Add/Remove programs, when the user tries to
uninstall a program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if not __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='UninstallString',
use_32bit_registry=use_32bit):
return True
return False
def skip_release_type(hive, key, sub_key, use_32bit):
'''
'ReleaseType' must either be absent or if present must not have a
value set to 'Security Update', 'Update Rollup', or 'Hotfix', because
that indicates it's an update to an existing program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if include_updates:
return False
skip_types = ['Hotfix',
'Security Update',
'Update Rollup']
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit):
if __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ReleaseType',
use_32bit_registry=use_32bit)['vdata'] in skip_types:
return True
return False
def skip_parent_key(hive, key, sub_key, use_32bit):
'''
'ParentKeyName' must NOT be present, because that indicates it's an
update to the parent program.
Returns:
bool: True if the package needs to be skipped, otherwise False
'''
if __utils__['reg.value_exists'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='ParentKeyName',
use_32bit_registry=use_32bit):
return True
return False
def add_software(hive, key, sub_key, use_32bit):
'''
'DisplayName' must be present with a valid value, as this is reflected
as the software name returned by pkg.list_pkgs. Also, its value must
not start with 'KB' followed by 6 numbers - as that indicates a
Windows update.
'''
d_name_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayName',
use_32bit_registry=use_32bit)
if (not d_name_regdata['success'] or
d_name_regdata['vtype'] not in ['REG_SZ', 'REG_EXPAND_SZ'] or
d_name_regdata['vdata'] in ['(value not set)', None, False]):
return
d_name = d_name_regdata['vdata']
if not include_updates:
if re.match(r'^KB[0-9]{6}', d_name):
return
d_vers_regdata = __utils__['reg.read_value'](
hive=hive,
key='{0}\\{1}'.format(key, sub_key),
vname='DisplayVersion',
use_32bit_registry=use_32bit)
d_vers = 'Not Found'
if (d_vers_regdata['success'] and
d_vers_regdata['vtype'] in ['REG_SZ', 'REG_EXPAND_SZ', 'REG_DWORD']):
if isinstance(d_vers_regdata['vdata'], int):
d_vers = six.text_type(d_vers_regdata['vdata'])
elif d_vers_regdata['vdata'] and d_vers_regdata['vdata'] != '(value not set)': # Check for blank values
d_vers = d_vers_regdata['vdata']
reg_software.setdefault(d_name, []).append(d_vers)
# Start gathering information from the registry
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 32 bit
kwargs['use_32bit'] = True
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# HKLM Uninstall 64 bit
kwargs = {'hive': 'HKLM',
'key': 'Software\\Classes\\Installer\\Products',
'use_32bit': False}
userdata_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\S-1-5-18\\Products'
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'], key=kwargs['key']):
# If the key does not exist in userdata, skip it
if not __utils__['reg.key_exists'](
hive=kwargs['hive'],
key='{0}\\{1}'.format(userdata_key, sub_key)):
continue
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 64 bit
# This has a propensity to take a while on a machine where many users have
# logged in. Untested in such a scenario
hive_hku = 'HKU'
uninstall_key = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
product_key = '{0}\\Software\\Microsoft\\Installer\\Products'
user_data_key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\' \
'UserData\\{0}\\Products\\{1}'
for user_guid in __utils__['reg.list_keys'](hive=hive_hku):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': False}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid)):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key),
'sub_key': 'InstallProperties',
'use_32bit': False}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
# Uninstall for each user on the system (HKU), 32 bit
for user_guid in __utils__['reg.list_keys'](hive=hive_hku,
use_32bit_registry=True):
kwargs = {'hive': hive_hku,
'key': uninstall_key.format(user_guid),
'use_32bit': True}
for sub_key in __utils__['reg.list_keys'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
kwargs['sub_key'] = sub_key
if skip_component(**kwargs):
continue
if skip_win_installer(**kwargs):
continue
if skip_uninstall_string(**kwargs):
continue
if skip_release_type(**kwargs):
continue
if skip_parent_key(**kwargs):
continue
add_software(**kwargs)
# While we have the user guid, we're gong to check userdata in HKLM
for sub_key_2 in __utils__['reg.list_keys'](hive=hive_hku,
key=product_key.format(user_guid),
use_32bit_registry=True):
kwargs = {'hive': 'HKLM',
'key': user_data_key.format(user_guid, sub_key_2),
'sub_key': 'InstallProperties',
'use_32bit': True}
if __utils__['reg.key_exists'](hive=kwargs['hive'],
key=kwargs['key'],
use_32bit_registry=kwargs['use_32bit']):
if skip_component(**kwargs):
continue
add_software(**kwargs)
return reg_software
def _refresh_db_conditional(saltenv, **kwargs):
'''
Internal use only in this module, has a different set of defaults and
returns True or False. And supports checking the age of the existing
generated metadata db, as well as ensure metadata db exists to begin with
Args:
saltenv (str): Salt environment
Kwargs:
force (bool):
Force a refresh if the minimum age has been reached. Default is
False.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed to
process.
Returns:
bool: True Fetched or Cache uptodate, False to indicate an issue
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
force = salt.utils.data.is_true(kwargs.pop('force', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', False))
expired_max = __opts__['winrepo_cache_expire_max']
expired_min = __opts__['winrepo_cache_expire_min']
repo_details = _get_repo_details(saltenv)
# Skip force if age less than minimum age
if force and expired_min > 0 and repo_details.winrepo_age < expired_min:
log.info(
'Refresh skipped, age of winrepo metadata in seconds (%s) is less '
'than winrepo_cache_expire_min (%s)',
repo_details.winrepo_age, expired_min
)
force = False
# winrepo_age is -1 if repo db does not exist
refresh = True if force \
or repo_details.winrepo_age == -1 \
or repo_details.winrepo_age > expired_max \
else False
if not refresh:
log.debug(
'Using existing pkg metadata db for saltenv \'%s\' (age is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
return True
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug(
'No winrepo.p cache file for saltenv \'%s\', creating one now',
saltenv
)
results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)
try:
# Return True if there were no failed winrepo SLS files, and False if
# failures were reported.
return not bool(results.get('failed', 0))
except AttributeError:
return False
def refresh_db(**kwargs):
r'''
Generates the local software metadata database (`winrepo.p`) on the minion.
The database is stored in a serialized format located by default at the
following location:
``C:\salt\var\cache\salt\minion\files\base\win\repo-ng\winrepo.p``
This module performs the following steps to generate the software metadata
database:
- Fetch the package definition files (.sls) from `winrepo_source_dir`
(default `salt://win/repo-ng`) and cache them in
`<cachedir>\files\<saltenv>\<winrepo_source_dir>`
(default: ``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``)
- Call :py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>` to parse the
package definition files and generate the repository metadata database
file (`winrepo.p`)
- Return the report received from
:py:func:`pkg.genrepo <salt.modules.win_pkg.genrepo>`
The default winrepo directory on the master is `/srv/salt/win/repo-ng`. All
files that end with `.sls` in this and all subdirectories will be used to
generate the repository metadata database (`winrepo.p`).
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
.. note::
There is no need to call `pkg.refresh_db` every time you work with the
pkg module. Automatic refresh will occur based on the following minion
configuration settings:
- `winrepo_cache_expire_min`
- `winrepo_cache_expire_max`
However, if the package definition files have changed, as would be the
case if you are developing a new package definition, this function
should be called to ensure the minion has the latest information about
packages available to it.
.. warning::
Directories and files fetched from <winrepo_source_dir>
(`/srv/salt/win/repo-ng`) will be processed in alphabetical order. If
two or more software definition files contain the same name, the last
one processed replaces all data from the files processed before it.
For more information see
:ref:`Windows Software Repository <windows-package-manager>`
Arguments:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return a verbose data structure which includes 'success_list', a
list of all sls files and the package names contained within.
Default is 'False'
failhard (bool):
If ``True``, an error will be raised if any repo SLS files fails to
process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
Returns:
dict: A dictionary containing the results of the database refresh.
.. note::
A result with a `total: 0` generally means that the files are in the
wrong location on the master. Try running the following command on the
minion: `salt-call -l debug pkg.refresh saltenv=base`
.. warning::
When calling this command from a state using `module.run` be sure to
pass `failhard: False`. Otherwise the state will report failure if it
encounters a bad software definition file.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db saltenv=base
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
__context__.pop('winrepo.data', None)
repo_details = _get_repo_details(saltenv)
log.debug(
'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
'metadata is %s)',
saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
)
# Clear minion repo-ng cache see #35342 discussion
log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
failed = []
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
for name in files:
if name.endswith('.sls'):
full_filename = os.path.join(root, name)
try:
os.remove(full_filename)
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s', full_filename, exc)
failed.append(full_filename)
if failed:
raise CommandExecutionError(
'Failed to clear one or more winrepo cache files',
info={'failed': failed}
)
# Cache repo-ng locally
log.info('Fetching *.sls files from %s', repo_details.winrepo_source_dir)
__salt__['cp.cache_dir'](
path=repo_details.winrepo_source_dir,
saltenv=saltenv,
include_pat='*.sls',
exclude_pat=r'E@\/\..*?\/' # Exclude all hidden directories (.git)
)
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = [__opts__['cachedir'], 'files', saltenv]
url_parts = _urlparse(winrepo_source_dir)
dirs.append(url_parts.netloc)
dirs.extend(url_parts.path.strip('/').split('/'))
local_dest = os.sep.join(dirs)
winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default
# Check for a valid windows file name
if not re.search(r'[\/:*?"<>|]',
__opts__['winrepo_cachefile'],
flags=re.IGNORECASE):
winrepo_file = os.path.join(
local_dest,
__opts__['winrepo_cachefile']
)
else:
log.error(
'minion configuration option \'winrepo_cachefile\' has been '
'ignored as its value (%s) is invalid. Please ensure this '
'option is set to a valid filename.',
__opts__['winrepo_cachefile']
)
# Do some safety checks on the repo_path as its contents can be removed,
# this includes check for bad coding
system_root = os.environ.get('SystemRoot', r'C:\Windows')
if not salt.utils.path.safe_path(
path=local_dest,
allow_path='\\'.join([system_root, 'TEMP'])):
raise CommandExecutionError(
'Attempting to delete files from a possibly unsafe location: '
'{0}'.format(local_dest)
)
__context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)
try:
os.makedirs(local_dest)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise CommandExecutionError(
'Failed to create {0}: {1}'.format(local_dest, exc)
)
winrepo_age = -1
try:
stat_result = os.stat(winrepo_file)
mtime = stat_result.st_mtime
winrepo_age = time.time() - mtime
except OSError as exc:
if exc.errno != errno.ENOENT:
raise CommandExecutionError(
'Failed to get age of {0}: {1}'.format(winrepo_file, exc)
)
except AttributeError:
# Shouldn't happen but log if it does
log.warning('st_mtime missing from stat result %s', stat_result)
except TypeError:
# Shouldn't happen but log if it does
log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)
repo_details = collections.namedtuple(
'RepoDetails',
('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')
)
return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)
def genrepo(**kwargs):
'''
Generate package metadata db based on files within the winrepo_source_dir
Kwargs:
saltenv (str): Salt environment. Default: ``base``
verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.
failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.
.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.
Returns:
dict: A dictionary of the results of the command
CLI Example:
.. code-block:: bash
salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base
'''
saltenv = kwargs.pop('saltenv', 'base')
verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
ret = {}
successful_verbose = {}
total_files_processed = 0
ret['repo'] = {}
ret['errors'] = {}
repo_details = _get_repo_details(saltenv)
for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
# Skip hidden directories (.git)
if re.search(r'[\\/]\..*', root):
log.debug('Skipping files in directory: %s', root)
continue
short_path = os.path.relpath(root, repo_details.local_dest)
if short_path == '.':
short_path = ''
for name in files:
if name.endswith('.sls'):
total_files_processed += 1
_repo_process_pkg_sls(
os.path.join(root, name),
os.path.join(short_path, name),
ret,
successful_verbose
)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
repo_cache.write(serial.dumps(ret))
# For some reason we can not save ret into __context__['winrepo.data'] as this breaks due to utf8 issues
successful_count = len(successful_verbose)
error_count = len(ret['errors'])
if verbose:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'success_list': successful_verbose,
'failed_list': ret['errors']
}
else:
if error_count > 0:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count,
'failed_list': ret['errors']
}
else:
results = {
'total': total_files_processed,
'success': successful_count,
'failed': error_count
}
if error_count > 0 and failhard:
raise CommandExecutionError(
'Error occurred while generating repo db',
info=results
)
else:
return results
def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
renderers = salt.loader.render(__opts__, __salt__)
def _failed_compile(prefix_msg, error_msg):
log.error('%s \'%s\': %s ', prefix_msg, short_path_name, error_msg)
ret.setdefault('errors', {})[short_path_name] = ['{0}, {1} '.format(prefix_msg, error_msg)]
return False
try:
config = salt.template.compile_template(
filename,
renderers,
__opts__['renderer'],
__opts__.get('renderer_blacklist', ''),
__opts__.get('renderer_whitelist', ''))
except SaltRenderError as exc:
return _failed_compile('Failed to compile', exc)
except Exception as exc:
return _failed_compile('Failed to read', exc)
if config and isinstance(config, dict):
revmap = {}
errors = []
for pkgname, version_list in six.iteritems(config):
if pkgname in ret['repo']:
log.error(
'package \'%s\' within \'%s\' already defined, skipping',
pkgname, short_path_name
)
errors.append('package \'{0}\' already defined'.format(pkgname))
break
for version_str, repodata in six.iteritems(version_list):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
continue
revmap[repodata['full_name']] = pkgname
if errors:
ret.setdefault('errors', {})[short_path_name] = errors
else:
ret.setdefault('repo', {}).update(config)
ret.setdefault('name_map', {}).update(revmap)
successful_verbose[short_path_name] = list(config.keys())
elif config:
return _failed_compile('Compiled contents', 'not a dictionary/hash')
else:
log.debug('No data within \'%s\' after processing', short_path_name)
# no pkgname found after render
successful_verbose[short_path_name] = []
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
# The source_hash is a file on a server
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
# The source_hash is a hash string
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret
def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
def install(name=None, refresh=False, pkgs=None, **kwargs):
r'''
Install the passed package(s) on the system using winrepo
Args:
name (str):
The name of a single package, or a comma-separated list of packages
to install. (no spaces after the commas)
refresh (bool):
Boolean value representing whether or not to refresh the winrepo db.
Default ``False``.
pkgs (list):
A list of packages to install from a software repository. All
packages listed under ``pkgs`` will be installed via a single
command.
You can specify a version by passing the item as a dict:
CLI Example:
.. code-block:: bash
# will install the latest version of foo and bar
salt '*' pkg.install pkgs='["foo", "bar"]'
# will install the latest version of foo and version 1.2.3 of bar
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Kwargs:
version (str):
The specific version to install. If omitted, the latest version will
be installed. Recommend for use when installing a single package.
If passed with a list of packages in the ``pkgs`` parameter, the
version will be ignored.
CLI Example:
.. code-block:: bash
# Version is ignored
salt '*' pkg.install pkgs="['foo', 'bar']" version=1.2.3
If passed with a comma separated list in the ``name`` parameter, the
version will apply to all packages in the list.
CLI Example:
.. code-block:: bash
# Version 1.2.3 will apply to packages foo and bar
salt '*' pkg.install foo,bar version=1.2.3
extra_install_flags (str):
Additional install flags that will be appended to the
``install_flags`` defined in the software definition file. Only
applies when single package is passed.
saltenv (str):
Salt environment. Default 'base'
report_reboot_exit_codes (bool):
If the installer exits with a recognized exit code indicating that
a reboot is required, the module function
*win_system.set_reboot_required_witnessed*
will be called, preserving the knowledge of this event for the
remainder of the current boot session. For the time being, 3010 is
the only recognized exit code. The value of this param defaults to
True.
.. versionadded:: 2016.11.0
Returns:
dict: Return a dict containing the new package names and versions. If
the package is already installed, an empty dict is returned.
If the package is installed by ``pkg.install``:
.. code-block:: cfg
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
The following example will refresh the winrepo and install a single
package, 7zip.
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip refresh=True
CLI Example:
.. code-block:: bash
salt '*' pkg.install 7zip
salt '*' pkg.install 7zip,filezilla
salt '*' pkg.install pkgs='["7zip","filezilla"]'
WinRepo Definition File Examples:
The following example demonstrates the use of ``cache_file``. This would be
used if you have multiple installers in the same directory that use the
same ``install.ini`` file and you don't want to download the additional
installers.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_file: 'salt://win/repo/ntp/install.ini'
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
The following example demonstrates the use of ``cache_dir``. It assumes a
file named ``install.ini`` resides in the same directory as the installer.
.. code-block:: bash
ntp:
4.2.8:
installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'
full_name: Meinberg NTP Windows Client
locale: en_US
reboot: False
cache_dir: True
install_flags: '/USEFILE=C:\salt\var\cache\salt\minion\files\base\win\repo\ntp\install.ini'
uninstaller: 'NTP/uninst.exe'
'''
ret = {}
saltenv = kwargs.pop('saltenv', 'base')
refresh = salt.utils.data.is_true(refresh)
# no need to call _refresh_db_conditional as list_pkgs will do it
# Make sure name or pkgs is passed
if not name and not pkgs:
return 'Must pass a single package or a list of packages'
# Ignore pkg_type from parse_targets, Windows does not support the
# "sources" argument
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]
if len(pkg_params) > 1:
if kwargs.get('extra_install_flags') is not None:
log.warning('\'extra_install_flags\' argument will be ignored for '
'multiple package targets')
# Windows expects an Options dictionary containing 'version'
for pkg in pkg_params:
pkg_params[pkg] = {'version': pkg_params[pkg]}
if not pkg_params:
log.error('No package definition found')
return {}
if not pkgs and len(pkg_params) == 1:
# Only use the 'version' param if a single item was passed to the 'name'
# parameter
pkg_params = {
name: {
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')
}
}
# Get a list of currently installed software for comparison at the end
old = list_pkgs(saltenv=saltenv, refresh=refresh, versions_as_list=True)
# Loop through each package
changed = []
for pkg_name, options in six.iteritems(pkg_params):
# Load package information for the package
pkginfo = _get_package_info(pkg_name, saltenv=saltenv)
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
version_num = options.get('version')
# Using the salt cmdline with version=5.3 might be interpreted
# as a float it must be converted to a string in order for
# string matching to work.
if not isinstance(version_num, six.string_types) and version_num is not None:
version_num = six.text_type(version_num)
# If the version was not passed, version_num will be None
if not version_num:
if pkg_name in old:
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, old[pkg_name][0])
continue
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
if version_num == 'latest' and 'latest' not in pkginfo:
# Get the most recent version number available from winrepo.p
# May also return `latest` or an empty string
version_num = _get_latest_pkg_version(pkginfo)
# Check if the version is already installed
if version_num in old.get(pkg_name, []):
# Desired version number already installed
log.debug('pkg.install: \'%s\' version \'%s\' is already installed',
pkg_name, version_num)
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
# Get the installer settings from winrepo.p
installer = pkginfo[version_num].get('installer', '')
cache_dir = pkginfo[version_num].get('cache_dir', False)
cache_file = pkginfo[version_num].get('cache_file', '')
# Is there an installer configured?
if not installer:
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
# Is the installer in a location that requires caching
if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):
# Check for the 'cache_dir' parameter in the .sls file
# If true, the entire directory will be cached instead of the
# individual file. This is useful for installations that are not
# single files
if cache_dir and installer.startswith('salt:'):
path, _ = os.path.split(installer)
__salt__['cp.cache_dir'](path=path,
saltenv=saltenv,
include_empty=False,
include_pat=None,
exclude_pat='E@init.sls$')
# Check to see if the cache_file is cached... if passed
if cache_file and cache_file.startswith('salt:'):
# Check to see if the file is cached
cached_file = __salt__['cp.is_cached'](cache_file, saltenv)
if not cached_file:
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Make sure the cached file is the same as the source
if __salt__['cp.hash_file'](cache_file, saltenv) != \
__salt__['cp.hash_file'](cached_file):
cached_file = __salt__['cp.cache_file'](cache_file, saltenv)
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
continue
# Check to see if the installer is cached
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
# Check if the installer was cached successfully
if not cached_pkg:
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
# Compare the hash of the cached installer to the source only if the
# file is hosted on salt:
if installer.startswith('salt:'):
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
try:
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
except MinionError as exc:
return '{0}: {1}'.format(exc, installer)
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
# Run the installer directly (not hosted on salt:, https:, etc.)
cached_pkg = installer
# Fix non-windows slashes
cached_pkg = cached_pkg.replace('/', '\\')
cache_path = os.path.dirname(cached_pkg)
# Compare the hash sums
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('pkg.install: Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('pkg.install: Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
("Source hash '{0}' does not match package hash"
" '{1}'").format(source_sum['hsum'], cached_pkg_sum)
)
log.debug('pkg.install: Source hash matches package hash.')
# Get install flags
install_flags = pkginfo[version_num].get('install_flags', '')
if options and options.get('extra_install_flags'):
install_flags = '{0} {1}'.format(
install_flags,
options.get('extra_install_flags', '')
)
# Compute msiexec string
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
# Build cmd and arguments
# cmd and arguments must be separated for use with the task scheduler
cmd_shell = os.getenv('ComSpec', '{0}\\system32\\cmd.exe'.format(os.getenv('WINDIR')))
if use_msiexec:
arguments = '"{0}" /I "{1}"'.format(msiexec, cached_pkg)
if pkginfo[version_num].get('allusers', True):
arguments = '{0} ALLUSERS=1'.format(arguments)
else:
arguments = '"{0}"'.format(cached_pkg)
if install_flags:
arguments = '{0} {1}'.format(arguments, install_flags)
# Install the software
# Check Use Scheduler Option
if pkginfo[version_num].get('use_scheduler', False):
# Create Scheduled Task
__salt__['task.create_task'](name='update-salt-software',
user_name='System',
force=True,
action_type='Execute',
cmd=cmd_shell,
arguments='/s /c "{0}"'.format(arguments),
start_in=cache_path,
trigger_type='Once',
start_date='1975-01-01',
start_time='01:00',
ac_only=False,
stop_if_on_batteries=False)
# Run Scheduled Task
# Special handling for installing salt
if re.search(r'salt[\s_.-]*minion',
pkg_name,
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Make sure the task is running, try for 5 secs
t_end = time.time() + 5
while time.time() < t_end:
time.sleep(0.25)
task_running = __salt__['task.status'](
'update-salt-software') == 'Running'
if task_running:
break
if not task_running:
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
# Launch the command
result = __salt__['cmd.run_all']('"{0}" /s /c "{1}"'.format(cmd_shell, arguments),
cache_path,
output_loglevel='trace',
python_shell=False,
redirect_stderr=True)
if not result['retcode']:
ret[pkg_name] = {'install status': 'success'}
changed.append(pkg_name)
elif result['retcode'] == 3010:
# 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
report_reboot_exit_codes = kwargs.pop(
'report_reboot_exit_codes', True)
if report_reboot_exit_codes:
__salt__['system.set_reboot_required_witnessed']()
ret[pkg_name] = {'install status': 'success, reboot required'}
changed.append(pkg_name)
elif result['retcode'] == 1641:
# 1641 is ERROR_SUCCESS_REBOOT_INITIATED
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
new = list_pkgs(saltenv=saltenv, refresh=False)
# Take the "old" package list and convert the values to strings in
# preparation for the comparison below.
__salt__['pkg_resource.stringify'](old)
# Check for changes in the registry
difference = salt.utils.data.compare_dicts(old, new)
# Compare the software list before and after
# Add the difference to ret
ret.update(difference)
return ret
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until implemented
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
saltenv = kwargs.get('saltenv', 'base')
log.warning('pkg.upgrade not implemented on Windows yet refresh:%s saltenv:%s', refresh, saltenv)
# Uncomment the below once pkg.upgrade has been implemented
# if salt.utils.data.is_true(refresh):
# refresh_db()
return {}
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
.. versionadded:: 0.16.0
Args:
name (str): The name of the package to be deleted.
version (str):
The version of the package to be deleted. If this option is
used in combination with the ``pkgs`` option below, then this
version will be applied to all targeted packages.
pkgs (list):
A list of packages to delete. Must be passed as a python
list. The ``name`` parameter will be ignored if this option is
passed.
Kwargs:
saltenv (str): Salt environment. Default ``base``
refresh (bool): Refresh package metadata. Default ``False``
Returns:
dict: A dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name,
pkgs=pkgs,
**kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
# we only call refresh_db if it does not exist, as we want to return
# the existing data even if its old, other parts of the code call this,
# but they will call refresh if they need too.
repo_details = _get_repo_details(saltenv)
if repo_details.winrepo_age == -1:
# no repo meta db
log.debug('No winrepo.p cache file. Refresh pkg db now.')
refresh_db(saltenv=saltenv)
if 'winrepo.data' in __context__:
log.trace('get_repo_data returning results from __context__')
return __context__['winrepo.data']
else:
log.trace('get_repo_data called reading from disk')
try:
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map(saltenv='base'):
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
u_name_map = {}
name_map = get_repo_data(saltenv).get('name_map', {})
if not six.PY2:
return name_map
for k in name_map:
u_name_map[k] = name_map[k]
return u_name_map
def _get_package_info(name, saltenv='base'):
'''
Return package info. Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data(saltenv).get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
return 1 if LooseVersion(pkg1) > LooseVersion(pkg2) else -1
def _get_latest_pkg_version(pkginfo):
'''
Returns the latest version of the package.
Will return 'latest' or version number string, and
'Not Found' if 'Not Found' is the only entry.
'''
if len(pkginfo) == 1:
return next(six.iterkeys(pkginfo))
try:
return sorted(
pkginfo,
key=cmp_to_key(_reverse_cmp_pkg_versions)
).pop()
except IndexError:
return ''
def compare_versions(ver1='', oper='==', ver2=''):
'''
Compare software package versions
Args:
ver1 (str): A software version to compare
oper (str): The operand to use to compare
ver2 (str): A software version to compare
Returns:
bool: True if the comparison is valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' pkg.compare_versions 1.2 >= 1.3
'''
if not ver1:
raise SaltInvocationError('compare_version, ver1 is blank')
if not ver2:
raise SaltInvocationError('compare_version, ver2 is blank')
# Support version being the special meaning of 'latest'
if ver1 == 'latest':
ver1 = six.text_type(sys.maxsize)
if ver2 == 'latest':
ver2 = six.text_type(sys.maxsize)
# Support version being the special meaning of 'Not Found'
if ver1 == 'Not Found':
ver1 = '0.0.0.0.0'
if ver2 == 'Not Found':
ver2 = '0.0.0.0.0'
return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.