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_system.py
join_domain
python
def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip())
Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L701-L785
[ "def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name\n only_on_pending_reboot=False):\n '''\n Reboot a running system.\n\n Args:\n\n timeout (int):\n The number of minutes/seconds before rebooting the system. Use of\n minutes or seconds depends on the value of ``in_seconds``. Default\n is 5 minutes.\n\n in_seconds (bool):\n ``True`` will cause the ``timeout`` parameter to be in seconds.\n ``False`` will be in minutes. Default is ``False``.\n\n .. versionadded:: 2015.8.0\n\n wait_for_reboot (bool)\n ``True`` will sleep for timeout + 30 seconds after reboot has been\n initiated. This is useful for use in a highstate. For example, you\n may have states that you want to apply only after the reboot.\n Default is ``False``.\n\n .. versionadded:: 2015.8.0\n\n only_on_pending_reboot (bool):\n If this is set to ``True``, then the reboot will only proceed\n if the system reports a pending reboot. Setting this parameter to\n ``True`` could be useful when calling this function from a final\n housekeeping state intended to be executed at the end of a state run\n (using *order: last*). Default is ``False``.\n\n Returns:\n bool: ``True`` if successful (a reboot will occur), otherwise ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.reboot 5\n salt '*' system.reboot 5 True\n\n Invoking this function from a final housekeeping state:\n\n .. code-block:: yaml\n\n final_housekeeping:\n module.run:\n - name: system.reboot\n - only_on_pending_reboot: True\n - order: last\n '''\n ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds,\n only_on_pending_reboot=only_on_pending_reboot)\n\n if wait_for_reboot:\n seconds = _convert_minutes_seconds(timeout, in_seconds)\n time.sleep(seconds + 30)\n\n return ret\n", "def _to_unicode(instr):\n '''\n Converts from current users character encoding to unicode.\n When instr has a value of None, the return value of the function\n will also be None.\n '''\n if instr is None or isinstance(instr, six.text_type):\n return instr\n else:\n return six.text_type(instr, 'utf8')\n", "def get_domain_workgroup():\n '''\n Get the domain or workgroup the computer belongs to.\n\n .. versionadded:: 2015.5.7\n .. versionadded:: 2015.8.2\n\n Returns:\n str: The name of the domain or workgroup\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion-id' system.get_domain_workgroup\n '''\n with salt.utils.winapi.Com():\n conn = wmi.WMI()\n for computer in conn.Win32_ComputerSystem():\n if computer.PartOfDomain:\n return {'Domain': computer.Domain}\n else:\n return {'Workgroup': computer.Workgroup}\n", "def _join_domain(domain,\n username=None,\n password=None,\n account_ou=None,\n account_exists=False):\n '''\n Helper function to join the domain.\n\n Args:\n domain (str): The domain to which the computer should be joined, e.g.\n ``example.com``\n\n username (str): Username of an account which is authorized to join\n computers to the specified domain. Need to be either fully qualified\n like ``user@domain.tld`` or simply ``user``\n\n password (str): Password of the specified user\n\n account_ou (str): The DN of the OU below which the account for this\n computer should be created when joining the domain, e.g.\n ``ou=computers,ou=departm_432,dc=my-company,dc=com``\n\n account_exists (bool): If set to ``True`` the computer will only join\n the domain if the account already exists. If set to ``False`` the\n computer account will be created if it does not exist, otherwise it\n will use the existing account. Default is False.\n\n Returns:\n int:\n\n :param domain:\n :param username:\n :param password:\n :param account_ou:\n :param account_exists:\n :return:\n '''\n NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name\n NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name\n NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name\n NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name\n\n join_options = 0x0\n join_options |= NETSETUP_JOIN_DOMAIN\n join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED\n join_options |= NETSETUP_JOIN_WITH_NEW_NAME\n if not account_exists:\n join_options |= NETSETUP_ACCOUNT_CREATE\n\n with salt.utils.winapi.Com():\n conn = wmi.WMI()\n comp = conn.Win32_ComputerSystem()[0]\n\n # Return the results of the command as an error\n # JoinDomainOrWorkgroup returns a strangely formatted value that looks like\n # (0,) so return the first item\n return comp.JoinDomainOrWorkgroup(\n Name=domain, Password=password, UserName=username, AccountOU=account_ou,\n FJoinOptions=join_options)[0]\n" ]
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
_join_domain
python
def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0]
Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L788-L846
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
unjoin_domain
python
def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False
Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L849-L954
[ "def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name\n only_on_pending_reboot=False):\n '''\n Reboot a running system.\n\n Args:\n\n timeout (int):\n The number of minutes/seconds before rebooting the system. Use of\n minutes or seconds depends on the value of ``in_seconds``. Default\n is 5 minutes.\n\n in_seconds (bool):\n ``True`` will cause the ``timeout`` parameter to be in seconds.\n ``False`` will be in minutes. Default is ``False``.\n\n .. versionadded:: 2015.8.0\n\n wait_for_reboot (bool)\n ``True`` will sleep for timeout + 30 seconds after reboot has been\n initiated. This is useful for use in a highstate. For example, you\n may have states that you want to apply only after the reboot.\n Default is ``False``.\n\n .. versionadded:: 2015.8.0\n\n only_on_pending_reboot (bool):\n If this is set to ``True``, then the reboot will only proceed\n if the system reports a pending reboot. Setting this parameter to\n ``True`` could be useful when calling this function from a final\n housekeeping state intended to be executed at the end of a state run\n (using *order: last*). Default is ``False``.\n\n Returns:\n bool: ``True`` if successful (a reboot will occur), otherwise ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.reboot 5\n salt '*' system.reboot 5 True\n\n Invoking this function from a final housekeeping state:\n\n .. code-block:: yaml\n\n final_housekeeping:\n module.run:\n - name: system.reboot\n - only_on_pending_reboot: True\n - order: last\n '''\n ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds,\n only_on_pending_reboot=only_on_pending_reboot)\n\n if wait_for_reboot:\n seconds = _convert_minutes_seconds(timeout, in_seconds)\n time.sleep(seconds + 30)\n\n return ret\n", "def _to_unicode(instr):\n '''\n Converts from current users character encoding to unicode.\n When instr has a value of None, the return value of the function\n will also be None.\n '''\n if instr is None or isinstance(instr, six.text_type):\n return instr\n else:\n return six.text_type(instr, 'utf8')\n", "def get_domain_workgroup():\n '''\n Get the domain or workgroup the computer belongs to.\n\n .. versionadded:: 2015.5.7\n .. versionadded:: 2015.8.2\n\n Returns:\n str: The name of the domain or workgroup\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion-id' system.get_domain_workgroup\n '''\n with salt.utils.winapi.Com():\n conn = wmi.WMI()\n for computer in conn.Win32_ComputerSystem():\n if computer.PartOfDomain:\n return {'Domain': computer.Domain}\n else:\n return {'Workgroup': computer.Workgroup}\n" ]
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
get_domain_workgroup
python
def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup}
Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L957-L979
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
set_domain_workgroup
python
def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False
Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L982-L1009
[ "def _to_unicode(instr):\n '''\n Converts from current users character encoding to unicode.\n When instr has a value of None, the return value of the function\n will also be None.\n '''\n if instr is None or isinstance(instr, six.text_type):\n return instr\n else:\n return six.text_type(instr, 'utf8')\n" ]
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
_try_parse_datetime
python
def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result
A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1012-L1032
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
get_system_time
python
def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian)
Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1035-L1058
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
set_system_date_time
python
def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err)
Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1096-L1179
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
set_system_date
python
def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day)
Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1199-L1233
[ "def _try_parse_datetime(time_str, fmts):\n '''\n A helper function that attempts to parse the input time_str as a date.\n\n Args:\n\n time_str (str): A string representing the time\n\n fmts (list): A list of date format strings\n\n Returns:\n datetime: Returns a datetime object if parsed properly, otherwise None\n '''\n result = None\n for fmt in fmts:\n try:\n result = datetime.strptime(time_str, fmt)\n break\n except ValueError:\n pass\n return result\n" ]
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
get_pending_component_servicing
python
def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False
Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1268-L1294
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
get_pending_domain_join
python
def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False
Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1297-L1332
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
get_pending_file_rename
python
def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False
Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1335-L1368
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
get_pending_servermanager
python
def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False
Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1371-L1407
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
get_pending_update
python
def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False
Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1410-L1434
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
set_reboot_required_witnessed
python
def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD')
r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1443-L1476
null
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1 def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
saltstack/salt
salt/modules/win_system.py
get_pending_reboot
python
def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the checks for reboot pending in most to least likely. checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join) for check in checks: if check(): return True return False
Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1508-L1537
[ "def get_reboot_required_witnessed():\n '''\n Determine if at any time during the current boot session the salt minion\n witnessed an event indicating that a reboot is required.\n\n This function will return ``True`` if an install completed with exit\n code 3010 during the current boot session and can be extended where\n appropriate in the future.\n\n .. versionadded:: 2016.11.0\n\n Returns:\n bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``,\n otherwise ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.get_reboot_required_witnessed\n\n '''\n value_dict = __utils__['reg.read_value'](\n hive='HKLM',\n key=MINION_VOLATILE_KEY,\n vname=REBOOT_REQUIRED_NAME)\n return value_dict['vdata'] == 1\n", "def get_pending_computer_name():\n '''\n Get a pending computer name. If the computer name has been changed, and the\n change is pending a system reboot, this function will return the pending\n computer name. Otherwise, ``None`` will be returned. If there was an error\n retrieving the pending computer name, ``False`` will be returned, and an\n error message will be logged to the minion log.\n\n Returns:\n str:\n Returns the pending name if pending restart. Returns ``None`` if not\n pending restart.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion-id' system.get_pending_computer_name\n '''\n current = get_computer_name()\n pending = __utils__['reg.read_value'](\n 'HKLM',\n r'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters',\n 'NV Hostname')['vdata']\n if pending:\n return pending if pending != current else None\n return False\n", "def get_pending_component_servicing():\n '''\n Determine whether there are pending Component Based Servicing tasks that\n require a reboot.\n\n .. versionadded:: 2016.11.0\n\n Returns:\n bool: ``True`` if there are pending Component Based Servicing tasks,\n otherwise ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.get_pending_component_servicing\n '''\n key = r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending'\n\n # So long as the registry key exists, a reboot is pending.\n if __utils__['reg.key_exists']('HKLM', key):\n log.debug('Key exists: %s', key)\n return True\n else:\n log.debug('Key does not exist: %s', key)\n\n return False\n", "def get_pending_domain_join():\n '''\n Determine whether there is a pending domain join action that requires a\n reboot.\n\n .. versionadded:: 2016.11.0\n\n Returns:\n bool: ``True`` if there is a pending domain join action, otherwise\n ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.get_pending_domain_join\n '''\n base_key = r'SYSTEM\\CurrentControlSet\\Services\\Netlogon'\n avoid_key = r'{0}\\AvoidSpnSet'.format(base_key)\n join_key = r'{0}\\JoinDomain'.format(base_key)\n\n # If either the avoid_key or join_key is present,\n # then there is a reboot pending.\n if __utils__['reg.key_exists']('HKLM', avoid_key):\n log.debug('Key exists: %s', avoid_key)\n return True\n else:\n log.debug('Key does not exist: %s', avoid_key)\n\n if __utils__['reg.key_exists']('HKLM', join_key):\n log.debug('Key exists: %s', join_key)\n return True\n else:\n log.debug('Key does not exist: %s', join_key)\n\n return False\n", "def get_pending_file_rename():\n '''\n Determine whether there are pending file rename operations that require a\n reboot.\n\n .. versionadded:: 2016.11.0\n\n Returns:\n bool: ``True`` if there are pending file rename operations, otherwise\n ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.get_pending_file_rename\n '''\n vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2')\n key = r'SYSTEM\\CurrentControlSet\\Control\\Session Manager'\n\n # If any of the value names exist and have value data set,\n # then a reboot is pending.\n\n for vname in vnames:\n reg_ret = __utils__['reg.read_value']('HKLM', key, vname)\n\n if reg_ret['success']:\n log.debug('Found key: %s', key)\n\n if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'):\n return True\n else:\n log.debug('Unable to access key: %s', key)\n return False\n", "def get_pending_servermanager():\n '''\n Determine whether there are pending Server Manager tasks that require a\n reboot.\n\n .. versionadded:: 2016.11.0\n\n Returns:\n bool: ``True`` if there are pending Server Manager tasks, otherwise\n ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.get_pending_servermanager\n '''\n vname = 'CurrentRebootAttempts'\n key = r'SOFTWARE\\Microsoft\\ServerManager'\n\n # There are situations where it's possible to have '(value not set)' as\n # the value data, and since an actual reboot won't be pending in that\n # instance, just catch instances where we try unsuccessfully to cast as int.\n\n reg_ret = __utils__['reg.read_value']('HKLM', key, vname)\n\n if reg_ret['success']:\n log.debug('Found key: %s', key)\n\n try:\n if int(reg_ret['vdata']) > 0:\n return True\n except ValueError:\n pass\n else:\n log.debug('Unable to access key: %s', key)\n return False\n", "def get_pending_update():\n '''\n Determine whether there are pending updates that require a reboot.\n\n .. versionadded:: 2016.11.0\n\n Returns:\n bool: ``True`` if there are pending updates, otherwise ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.get_pending_update\n '''\n key = r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired'\n\n # So long as the registry key exists, a reboot is pending.\n if __utils__['reg.key_exists']('HKLM', key):\n log.debug('Key exists: %s', key)\n return True\n else:\n log.debug('Key does not exist: %s', key)\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module for managing windows systems. :depends: - pywintypes - win32api - win32con - win32net - wmi Support for reboot, shutdown, etc ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import ctypes import logging import time import platform from datetime import datetime # Import salt libs import salt.utils.functools import salt.utils.locales import salt.utils.platform import salt.utils.winapi from salt.exceptions import CommandExecutionError # Import 3rd-party Libs from salt.ext import six try: import wmi import win32net import win32api import win32con import pywintypes from ctypes import windll HAS_WIN32NET_MODS = True except ImportError: HAS_WIN32NET_MODS = False # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'system' def __virtual__(): ''' Only works on Windows Systems with Win32 Modules ''' if not salt.utils.platform.is_windows(): return False, 'Module win_system: Requires Windows' if not HAS_WIN32NET_MODS: return False, 'Module win_system: Missing win32 modules' return __virtualname__ def _convert_minutes_seconds(timeout, in_seconds=False): ''' convert timeout to seconds ''' return timeout if in_seconds else timeout*60 def _convert_date_time_string(dt_string): ''' convert string to date time object ''' dt_string = dt_string.split('.')[0] dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S') return dt_obj.strftime('%Y-%m-%d %H:%M:%S') def _to_unicode(instr): ''' Converts from current users character encoding to unicode. When instr has a value of None, the return value of the function will also be None. ''' if instr is None or isinstance(instr, six.text_type): return instr else: return six.text_type(instr, 'utf8') def halt(timeout=5, in_seconds=False): ''' Halt a running system. Args: timeout (int): Number of seconds before halting the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.halt 5 True ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def init(runlevel): # pylint: disable=unused-argument ''' Change the system runlevel on sysV compatible systems. Not applicable to Windows CLI Example: .. code-block:: bash salt '*' system.init 3 ''' # cmd = ['init', runlevel] # ret = __salt__['cmd.run'](cmd, python_shell=False) # return ret # TODO: Create a mapping of runlevels to # pylint: disable=fixme # corresponding Windows actions return 'Not implemented on Windows at this time.' def poweroff(timeout=5, in_seconds=False): ''' Power off a running system. Args: timeout (int): Number of seconds before powering off the system. Default is 5 seconds. in_seconds (bool): Whether to treat timeout as seconds or minutes. .. versionadded:: 2015.8.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.poweroff 5 ''' return shutdown(timeout=timeout, in_seconds=in_seconds) def reboot(timeout=5, in_seconds=False, wait_for_reboot=False, # pylint: disable=redefined-outer-name only_on_pending_reboot=False): ''' Reboot a running system. Args: timeout (int): The number of minutes/seconds before rebooting the system. Use of minutes or seconds depends on the value of ``in_seconds``. Default is 5 minutes. in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 wait_for_reboot (bool) ``True`` will sleep for timeout + 30 seconds after reboot has been initiated. This is useful for use in a highstate. For example, you may have states that you want to apply only after the reboot. Default is ``False``. .. versionadded:: 2015.8.0 only_on_pending_reboot (bool): If this is set to ``True``, then the reboot will only proceed if the system reports a pending reboot. Setting this parameter to ``True`` could be useful when calling this function from a final housekeeping state intended to be executed at the end of a state run (using *order: last*). Default is ``False``. Returns: bool: ``True`` if successful (a reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.reboot 5 salt '*' system.reboot 5 True Invoking this function from a final housekeeping state: .. code-block:: yaml final_housekeeping: module.run: - name: system.reboot - only_on_pending_reboot: True - order: last ''' ret = shutdown(timeout=timeout, reboot=True, in_seconds=in_seconds, only_on_pending_reboot=only_on_pending_reboot) if wait_for_reboot: seconds = _convert_minutes_seconds(timeout, in_seconds) time.sleep(seconds + 30) return ret def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. timeout (int): The length of time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be aborted using the ``system.shutdown_abort`` function. If timeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows (system modal). The dialog box can be moved but not closed. A timer counts down the remaining time before the shutdown occurs. If timeout is zero, the computer shuts down immediately without displaying the dialog box and cannot be stopped by ``system.shutdown_abort``. Default is 5 minutes in_seconds (bool): ``True`` will cause the ``timeout`` parameter to be in seconds. ``False`` will be in minutes. Default is ``False``. .. versionadded:: 2015.8.0 force_close (bool): ``True`` will force close all open applications. ``False`` will display a dialog box instructing the user to close open applications. Default is ``True``. reboot (bool): ``True`` restarts the computer immediately after shutdown. ``False`` powers down the system. Default is ``False``. only_on_pending_reboot (bool): If this is set to True, then the shutdown will only proceed if the system reports a pending reboot. To optionally shutdown in a highstate, consider using the shutdown state instead of this module. only_on_pending_reboot (bool): If ``True`` the shutdown will only proceed if there is a reboot pending. ``False`` will shutdown the system. Default is ``False``. Returns: bool: ``True`` if successful (a shutdown or reboot will occur), otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown "System will shutdown in 5 minutes" ''' if six.PY2: message = _to_unicode(message) timeout = _convert_minutes_seconds(timeout, in_seconds) if only_on_pending_reboot and not get_pending_reboot(): return False if message and not isinstance(message, six.string_types): message = message.decode('utf-8') try: win32api.InitiateSystemShutdown('127.0.0.1', message, timeout, force_close, reboot) return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to shutdown the system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def shutdown_hard(): ''' Shutdown a running system with no timeout or warning. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.shutdown_hard ''' return shutdown(timeout=0) def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.shutdown_abort ''' try: win32api.AbortSystemShutdown('127.0.0.1') return True except pywintypes.error as exc: (number, context, message) = exc.args log.error('Failed to abort system shutdown') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False def lock(): ''' Lock the workstation. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.lock ''' return windll.user32.LockWorkStation() def set_computer_name(name): ''' Set the Windows computer name Args: name (str): The new name to give the computer. Requires a reboot to take effect. Returns: dict: Returns a dictionary containing the old and new names if successful. ``False`` if not. CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_name 'DavesComputer' ''' if six.PY2: name = _to_unicode(name) if windll.kernel32.SetComputerNameExW( win32con.ComputerNamePhysicalDnsHostname, name): ret = {'Computer Name': {'Current': get_computer_name()}} pending = get_pending_computer_name() if pending not in (None, False): ret['Computer Name']['Pending'] = pending return ret return False def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, ``False`` will be returned, and an error message will be logged to the minion log. Returns: str: Returns the pending name if pending restart. Returns ``None`` if not pending restart. CLI Example: .. code-block:: bash salt 'minion-id' system.get_pending_computer_name ''' current = get_computer_name() pending = __utils__['reg.read_value']( 'HKLM', r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'NV Hostname')['vdata'] if pending: return pending if pending != current else None return False def get_computer_name(): ''' Get the Windows computer name Returns: str: Returns the computer name if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_name ''' name = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) return name if name else False def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' ''' if six.PY2: desc = _to_unicode(desc) # Make sure the system exists # Return an object containing current information array for the computer system_info = win32net.NetServerGetInfo(None, 101) # If desc is passed, decode it for unicode if desc is None: return False system_info['comment'] = desc # Apply new settings try: win32net.NetServerSetInfo(None, 101, system_info) except win32net.error as exc: (number, context, message) = exc.args log.error('Failed to update system') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False return {'Computer Description': get_computer_desc()} set_computer_description = salt.utils.functools.alias_function(set_computer_desc, 'set_computer_description') # pylint: disable=invalid-name def get_system_info(): ''' Get system information. Returns: dict: Dictionary containing information about the system to include name, description, version, etc... CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_info ''' def byte_calc(val): val = float(val) if val < 2**10: return '{0:.3f}B'.format(val) elif val < 2**20: return '{0:.3f}KB'.format(val / 2**10) elif val < 2**30: return '{0:.3f}MB'.format(val / 2**20) elif val < 2**40: return '{0:.3f}GB'.format(val / 2**30) else: return '{0:.3f}TB'.format(val / 2**40) # Lookup dicts for Win32_OperatingSystem os_type = {1: 'Work Station', 2: 'Domain Controller', 3: 'Server'} # lookup dicts for Win32_ComputerSystem domain_role = {0: 'Standalone Workstation', 1: 'Member Workstation', 2: 'Standalone Server', 3: 'Member Server', 4: 'Backup Domain Controller', 5: 'Primary Domain Controller'} warning_states = {1: 'Other', 2: 'Unknown', 3: 'Safe', 4: 'Warning', 5: 'Critical', 6: 'Non-recoverable'} pc_system_types = {0: 'Unspecified', 1: 'Desktop', 2: 'Mobile', 3: 'Workstation', 4: 'Enterprise Server', 5: 'SOHO Server', 6: 'Appliance PC', 7: 'Performance Server', 8: 'Maximum'} # Connect to WMI with salt.utils.winapi.Com(): conn = wmi.WMI() system = conn.Win32_OperatingSystem()[0] ret = {'name': get_computer_name(), 'description': system.Description, 'install_date': system.InstallDate, 'last_boot': system.LastBootUpTime, 'os_manufacturer': system.Manufacturer, 'os_name': system.Caption, 'users': system.NumberOfUsers, 'organization': system.Organization, 'os_architecture': system.OSArchitecture, 'primary': system.Primary, 'os_type': os_type[system.ProductType], 'registered_user': system.RegisteredUser, 'system_directory': system.SystemDirectory, 'system_drive': system.SystemDrive, 'os_version': system.Version, 'windows_directory': system.WindowsDirectory} system = conn.Win32_ComputerSystem()[0] # Get pc_system_type depending on Windows version if platform.release() in ['Vista', '7', '8']: # Types for Vista, 7, and 8 pc_system_type = pc_system_types[system.PCSystemType] else: # New types were added with 8.1 and newer pc_system_types.update({8: 'Slate', 9: 'Maximum'}) pc_system_type = pc_system_types[system.PCSystemType] ret.update({ 'bootup_state': system.BootupState, 'caption': system.Caption, 'chassis_bootup_state': warning_states[system.ChassisBootupState], 'chassis_sku_number': system.ChassisSKUNumber, 'dns_hostname': system.DNSHostname, 'domain': system.Domain, 'domain_role': domain_role[system.DomainRole], 'hardware_manufacturer': system.Manufacturer, 'hardware_model': system.Model, 'network_server_mode_enabled': system.NetworkServerModeEnabled, 'part_of_domain': system.PartOfDomain, 'pc_system_type': pc_system_type, 'power_state': system.PowerState, 'status': system.Status, 'system_type': system.SystemType, 'total_physical_memory': byte_calc(system.TotalPhysicalMemory), 'total_physical_memory_raw': system.TotalPhysicalMemory, 'thermal_state': warning_states[system.ThermalState], 'workgroup': system.Workgroup }) # Get processor information processors = conn.Win32_Processor() ret['processors'] = 0 ret['processors_logical'] = 0 ret['processor_cores'] = 0 ret['processor_cores_enabled'] = 0 ret['processor_manufacturer'] = processors[0].Manufacturer ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz' for processor in processors: ret['processors'] += 1 ret['processors_logical'] += processor.NumberOfLogicalProcessors ret['processor_cores'] += processor.NumberOfCores ret['processor_cores_enabled'] += processor.NumberOfEnabledCore bios = conn.Win32_BIOS()[0] ret.update({'hardware_serial': bios.SerialNumber, 'bios_manufacturer': bios.Manufacturer, 'bios_version': bios.Version, 'bios_details': bios.BIOSVersion, 'bios_caption': bios.Caption, 'bios_description': bios.Description}) ret['install_date'] = _convert_date_time_string(ret['install_date']) ret['last_boot'] = _convert_date_time_string(ret['last_boot']) return ret def get_computer_desc(): ''' Get the Windows computer description Returns: str: Returns the computer description if found. Otherwise returns ``False``. CLI Example: .. code-block:: bash salt 'minion-id' system.get_computer_desc ''' desc = get_system_info()['description'] return False if desc is None else desc get_computer_description = salt.utils.functools.alias_function(get_computer_desc, 'get_computer_description') # pylint: disable=invalid-name def get_hostname(): ''' Get the hostname of the windows minion .. versionadded:: 2016.3.0 Returns: str: Returns the hostname of the windows minion CLI Example: .. code-block:: bash salt 'minion-id' system.get_hostname ''' cmd = 'hostname' ret = __salt__['cmd.run'](cmd=cmd) return ret def set_hostname(hostname): ''' Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname ''' with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname) def join_domain(domain, username=None, password=None, account_ou=None, account_exists=False, restart=False): ''' Join a computer to an Active Directory domain. Requires a reboot. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Needs to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is ``False`` restart (bool): ``True`` will restart the computer after a successful join. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.join_domain domain='domain.tld' \\ username='joinuser' password='joinpassword' \\ account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\ account_exists=False, restart=True ''' if six.PY2: domain = _to_unicode(domain) username = _to_unicode(username) password = _to_unicode(password) account_ou = _to_unicode(account_ou) status = get_domain_workgroup() if 'Domain' in status: if status['Domain'] == domain: return 'Already joined to {0}'.format(domain) if username and '\\' not in username and '@' not in username: username = '{0}@{1}'.format(username, domain) if username and password is None: return 'Must specify a password if you pass a username' # remove any escape characters if isinstance(account_ou, six.string_types): account_ou = account_ou.split('\\') account_ou = ''.join(account_ou) err = _join_domain(domain=domain, username=username, password=password, account_ou=account_ou, account_exists=account_exists) if not err: ret = {'Domain': domain, 'Restart': False} if restart: ret['Restart'] = reboot() return ret raise CommandExecutionError(win32api.FormatMessage(err).rstrip()) def _join_domain(domain, username=None, password=None, account_ou=None, account_exists=False): ''' Helper function to join the domain. Args: domain (str): The domain to which the computer should be joined, e.g. ``example.com`` username (str): Username of an account which is authorized to join computers to the specified domain. Need to be either fully qualified like ``user@domain.tld`` or simply ``user`` password (str): Password of the specified user account_ou (str): The DN of the OU below which the account for this computer should be created when joining the domain, e.g. ``ou=computers,ou=departm_432,dc=my-company,dc=com`` account_exists (bool): If set to ``True`` the computer will only join the domain if the account already exists. If set to ``False`` the computer account will be created if it does not exist, otherwise it will use the existing account. Default is False. Returns: int: :param domain: :param username: :param password: :param account_ou: :param account_exists: :return: ''' NETSETUP_JOIN_DOMAIN = 0x1 # pylint: disable=invalid-name NETSETUP_ACCOUNT_CREATE = 0x2 # pylint: disable=invalid-name NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20 # pylint: disable=invalid-name NETSETUP_JOIN_WITH_NEW_NAME = 0x400 # pylint: disable=invalid-name join_options = 0x0 join_options |= NETSETUP_JOIN_DOMAIN join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED join_options |= NETSETUP_JOIN_WITH_NEW_NAME if not account_exists: join_options |= NETSETUP_ACCOUNT_CREATE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Return the results of the command as an error # JoinDomainOrWorkgroup returns a strangely formatted value that looks like # (0,) so return the first item return comp.JoinDomainOrWorkgroup( Name=domain, Password=password, UserName=username, AccountOU=account_ou, FJoinOptions=join_options)[0] def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. Requires a restart. Args: username (str): Username of an account which is authorized to manage computer accounts on the domain. Needs to be a fully qualified name like ``user@domain.tld`` or ``domain.tld\\user``. If the domain is not specified, the passed domain will be used. If the computer account doesn't need to be disabled after the computer is unjoined, this can be ``None``. password (str): The password of the specified user domain (str): The domain from which to unjoin the computer. Can be ``None`` workgroup (str): The workgroup to join the computer to. Default is ``WORKGROUP`` .. versionadded:: 2015.8.2/2015.5.7 disable (bool): ``True`` to disable the computer account in Active Directory. Default is ``False`` restart (bool): ``True`` will restart the computer after successful unjoin. Default is ``False`` .. versionadded:: 2015.8.2/2015.5.7 Returns: dict: Returns a dictionary if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.unjoin_domain restart=True salt 'minion-id' system.unjoin_domain username='unjoinuser' \\ password='unjoinpassword' disable=True \\ restart=True ''' # pylint: enable=anomalous-backslash-in-string if six.PY2: username = _to_unicode(username) password = _to_unicode(password) domain = _to_unicode(domain) status = get_domain_workgroup() if 'Workgroup' in status: if status['Workgroup'] == workgroup: return 'Already joined to {0}'.format(workgroup) if username and '\\' not in username and '@' not in username: if domain: username = '{0}@{1}'.format(username, domain) else: return 'Must specify domain if not supplied in username' if username and password is None: return 'Must specify a password if you pass a username' NETSETUP_ACCT_DELETE = 0x4 # pylint: disable=invalid-name unjoin_options = 0x0 if disable: unjoin_options |= NETSETUP_ACCT_DELETE with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] err = comp.UnjoinDomainOrWorkgroup(Password=password, UserName=username, FUnjoinOptions=unjoin_options) # you have to do this because UnjoinDomainOrWorkgroup returns a # strangely formatted value that looks like (0,) if not err[0]: err = comp.JoinDomainOrWorkgroup(Name=workgroup) if not err[0]: ret = {'Workgroup': workgroup, 'Restart': False} if restart: ret['Restart'] = reboot() return ret else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to join the computer to %s', workgroup) return False else: log.error(win32api.FormatMessage(err[0]).rstrip()) log.error('Failed to unjoin computer from %s', status['Domain']) return False def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup} def set_domain_workgroup(workgroup): ''' Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL ''' if six.PY2: workgroup = _to_unicode(workgroup) # Initialize COM with salt.utils.winapi.Com(): # Grab the first Win32_ComputerSystem object from wmi conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] # Now we can join the new workgroup res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return True if not res[0] else False def _try_parse_datetime(time_str, fmts): ''' A helper function that attempts to parse the input time_str as a date. Args: time_str (str): A string representing the time fmts (list): A list of date format strings Returns: datetime: Returns a datetime object if parsed properly, otherwise None ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if hours == 12: meridian = 'PM' elif hours == 0: hours = 12 elif hours > 12: hours = hours - 12 meridian = 'PM' return '{0:02d}:{1:02d}:{2:02d} {3}'.format(hours, now[5], now[6], meridian) def set_system_time(newtime): ''' Set the system time. Args: newtime (str): The time to set. Can be any of the following formats: - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_system_time 12:01 ''' # Get date/time object from newtime fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second) def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Args: years (int): Years digit, ie: 2015 months (int): Months digit: 1 - 12 days (int): Days digit: 1 - 31 hours (int): Hours digit: 0 - 23 minutes (int): Minutes digit: 0 - 59 seconds (int): Seconds digit: 0 - 59 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date_ time 2015 5 12 11 37 53 ''' # Get the current date/time try: date_time = win32api.GetLocalTime() except win32api.error as exc: (number, context, message) = exc.args log.error('Failed to get local time') log.error('nbr: %s', number) log.error('ctx: %s', context) log.error('msg: %s', message) return False # Check for passed values. If not passed, use current values if years is None: years = date_time[0] if months is None: months = date_time[1] if days is None: days = date_time[3] if hours is None: hours = date_time[4] if minutes is None: minutes = date_time[5] if seconds is None: seconds = date_time[6] try: class SYSTEMTIME(ctypes.Structure): _fields_ = [ ('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16), ('wDayOfWeek', ctypes.c_int16), ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16), ('wMinute', ctypes.c_int16), ('wSecond', ctypes.c_int16), ('wMilliseconds', ctypes.c_int16)] system_time = SYSTEMTIME() system_time.wYear = int(years) system_time.wMonth = int(months) system_time.wDay = int(days) system_time.wHour = int(hours) system_time.wMinute = int(minutes) system_time.wSecond = int(seconds) system_time_ptr = ctypes.pointer(system_time) succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr) if succeeded is not 0: return True else: log.error('Failed to set local time') raise CommandExecutionError( win32api.FormatMessage(succeeded).rstrip()) except OSError as err: log.error('Failed to set local time') raise CommandExecutionError(err) def get_system_date(): ''' Get the Windows system date Returns: str: Returns the system date CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' now = win32api.GetLocalTime() return '{0:02d}/{1:02d}/{2:04d}'.format(now[1], now[3], now[0]) def set_system_date(newdate): ''' Set the Windows system date. Use <mm-dd-yy> format for the date. Args: newdate (str): The date to set. Can be any of the following formats - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: return False # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day) def start_time_service(): ''' Start the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.start_time_service ''' return __salt__['service.start']('w32time') def stop_time_service(): ''' Stop the Windows time service Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.stop_time_service ''' return __salt__['service.stop']('w32time') def get_pending_component_servicing(): ''' Determine whether there are pending Component Based Servicing tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Component Based Servicing tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_component_servicing ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False def get_pending_domain_join(): ''' Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join ''' base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) # If either the avoid_key or join_key is present, # then there is a reboot pending. if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True else: log.debug('Key does not exist: %s', avoid_key) if __utils__['reg.key_exists']('HKLM', join_key): log.debug('Key exists: %s', join_key) return True else: log.debug('Key does not exist: %s', join_key) return False def get_pending_file_rename(): ''' Determine whether there are pending file rename operations that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending file rename operations, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_file_rename ''' vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2') key = r'SYSTEM\CurrentControlSet\Control\Session Manager' # If any of the value names exist and have value data set, # then a reboot is pending. for vname in vnames: reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'): return True else: log.debug('Unable to access key: %s', key) return False def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager ''' vname = 'CurrentRebootAttempts' key = r'SOFTWARE\Microsoft\ServerManager' # There are situations where it's possible to have '(value not set)' as # the value data, and since an actual reboot won't be pending in that # instance, just catch instances where we try unsuccessfully to cast as int. reg_ret = __utils__['reg.read_value']('HKLM', key, vname) if reg_ret['success']: log.debug('Found key: %s', key) try: if int(reg_ret['vdata']) > 0: return True except ValueError: pass else: log.debug('Unable to access key: %s', key) return False def get_pending_update(): ''' Determine whether there are pending updates that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending updates, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_update ''' key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' # So long as the registry key exists, a reboot is pending. if __utils__['reg.key_exists']('HKLM', key): log.debug('Key exists: %s', key) return True else: log.debug('Key does not exist: %s', key) return False MINION_VOLATILE_KEY = r'SYSTEM\CurrentControlSet\Services\salt-minion\Volatile-Data' REBOOT_REQUIRED_NAME = 'Reboot required' def set_reboot_required_witnessed(): r''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function relies on the salt-minion's ability to create the following volatile registry key in the *HKLM* hive: *SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data* Because this registry key is volatile, it will not persist beyond the current boot session. Also, in the scope of this key, the name *'Reboot required'* will be assigned the value of *1*. For the time being, this function is being used whenever an install completes with exit code 3010 and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' return __utils__['reg.set_value']( hive='HKLM', key=MINION_VOLATILE_KEY, volatile=True, vname=REBOOT_REQUIRED_NAME, vdata=1, vtype='REG_DWORD') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. This function will return ``True`` if an install completed with exit code 3010 during the current boot session and can be extended where appropriate in the future. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the ``Requires reboot`` registry flag is set to ``1``, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' value_dict = __utils__['reg.read_value']( hive='HKLM', key=MINION_VOLATILE_KEY, vname=REBOOT_REQUIRED_NAME) return value_dict['vdata'] == 1
saltstack/salt
salt/states/postgres_extension.py
present
python
def present(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, maintenance_db=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Ensure that the named extension is present. .. note:: Before you can use the state to load an extension into a database, the extension's supporting files must be already installed. For more information about all of these options see ``CREATE EXTENSION`` SQL command reference in the PostgreSQL documentation. name The name of the extension to be installed if_not_exists Add an ``IF NOT EXISTS`` parameter to the DDL statement schema Schema to install the extension into ext_version Version to install from_version Old extension version if already installed user System user all operations should be performed on behalf of maintenance_db Database to act on 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': 'Extension {0} is already present'.format(name)} db_args = { 'maintenance_db': maintenance_db, 'runas': user, 'user': db_user, 'password': db_password, 'host': db_host, 'port': db_port, } # check if extension exists mode = 'create' mtdata = __salt__['postgres.create_metadata']( name, schema=schema, ext_version=ext_version, **db_args) # The extension is not present, install it! toinstall = postgres._EXTENSION_NOT_INSTALLED in mtdata if toinstall: mode = 'install' toupgrade = False if postgres._EXTENSION_INSTALLED in mtdata: for flag in [ postgres._EXTENSION_TO_MOVE, postgres._EXTENSION_TO_UPGRADE ]: if flag in mtdata: toupgrade = True mode = 'upgrade' cret = None if toinstall or toupgrade: if __opts__['test']: ret['result'] = None if mode: ret['comment'] = 'Extension {0} is set to be {1}ed'.format( name, mode).replace('eed', 'ed') return ret cret = __salt__['postgres.create_extension']( name=name, if_not_exists=if_not_exists, schema=schema, ext_version=ext_version, from_version=from_version, **db_args) if cret: if mode.endswith('e'): suffix = 'd' else: suffix = 'ed' ret['comment'] = 'The extension {0} has been {1}{2}'.format(name, mode, suffix) ret['changes'][name] = '{0}{1}'.format(mode.capitalize(), suffix) elif cret is not None: ret['comment'] = 'Failed to {1} extension {0}'.format(name, mode) ret['result'] = False return ret
Ensure that the named extension is present. .. note:: Before you can use the state to load an extension into a database, the extension's supporting files must be already installed. For more information about all of these options see ``CREATE EXTENSION`` SQL command reference in the PostgreSQL documentation. name The name of the extension to be installed if_not_exists Add an ``IF NOT EXISTS`` parameter to the DDL statement schema Schema to install the extension into ext_version Version to install from_version Old extension version if already installed user System user all operations should be performed on behalf of maintenance_db Database to act on 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_extension.py#L36-L151
null
# -*- coding: utf-8 -*- ''' Management of PostgreSQL extensions =================================== A module used to install and manage PostgreSQL extensions. .. code-block:: yaml adminpack: postgres_extension.present .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs from salt.modules import postgres log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the postgres module is present ''' if 'postgres.create_extension' not in __salt__: return (False, 'Unable to load postgres module. Make sure `postgres.bins_dir` is set.') return True def absent(name, if_exists=None, restrict=None, cascade=None, user=None, maintenance_db=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Ensure that the named extension is absent. name Extension name of the extension to remove if_exists Add if exist slug restrict Add restrict slug cascade Drop on cascade user System user all operations should be performed on behalf of maintenance_db Database to act on 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 extension exists and remove it exists = __salt__['postgres.is_installed_extension'](name, **db_args) if exists: if __opts__['test']: ret['result'] = None ret['comment'] = 'Extension {0} is set to be removed'.format(name) return ret if __salt__['postgres.drop_extension'](name, if_exists=if_exists, restrict=restrict, cascade=cascade, **db_args): ret['comment'] = 'Extension {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret else: ret['result'] = False ret['comment'] = 'Extension {0} failed to be removed'.format(name) return ret else: ret['comment'] = 'Extension {0} is not present, so it cannot ' \ 'be removed'.format(name) return ret
saltstack/salt
salt/states/postgres_extension.py
absent
python
def absent(name, if_exists=None, restrict=None, cascade=None, user=None, maintenance_db=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Ensure that the named extension is absent. name Extension name of the extension to remove if_exists Add if exist slug restrict Add restrict slug cascade Drop on cascade user System user all operations should be performed on behalf of maintenance_db Database to act on 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 extension exists and remove it exists = __salt__['postgres.is_installed_extension'](name, **db_args) if exists: if __opts__['test']: ret['result'] = None ret['comment'] = 'Extension {0} is set to be removed'.format(name) return ret if __salt__['postgres.drop_extension'](name, if_exists=if_exists, restrict=restrict, cascade=cascade, **db_args): ret['comment'] = 'Extension {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret else: ret['result'] = False ret['comment'] = 'Extension {0} failed to be removed'.format(name) return ret else: ret['comment'] = 'Extension {0} is not present, so it cannot ' \ 'be removed'.format(name) return ret
Ensure that the named extension is absent. name Extension name of the extension to remove if_exists Add if exist slug restrict Add restrict slug cascade Drop on cascade user System user all operations should be performed on behalf of maintenance_db Database to act on 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_extension.py#L154-L232
null
# -*- coding: utf-8 -*- ''' Management of PostgreSQL extensions =================================== A module used to install and manage PostgreSQL extensions. .. code-block:: yaml adminpack: postgres_extension.present .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging # Import salt libs from salt.modules import postgres log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the postgres module is present ''' if 'postgres.create_extension' not in __salt__: return (False, 'Unable to load postgres module. Make sure `postgres.bins_dir` is set.') return True def present(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, maintenance_db=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Ensure that the named extension is present. .. note:: Before you can use the state to load an extension into a database, the extension's supporting files must be already installed. For more information about all of these options see ``CREATE EXTENSION`` SQL command reference in the PostgreSQL documentation. name The name of the extension to be installed if_not_exists Add an ``IF NOT EXISTS`` parameter to the DDL statement schema Schema to install the extension into ext_version Version to install from_version Old extension version if already installed user System user all operations should be performed on behalf of maintenance_db Database to act on 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': 'Extension {0} is already present'.format(name)} db_args = { 'maintenance_db': maintenance_db, 'runas': user, 'user': db_user, 'password': db_password, 'host': db_host, 'port': db_port, } # check if extension exists mode = 'create' mtdata = __salt__['postgres.create_metadata']( name, schema=schema, ext_version=ext_version, **db_args) # The extension is not present, install it! toinstall = postgres._EXTENSION_NOT_INSTALLED in mtdata if toinstall: mode = 'install' toupgrade = False if postgres._EXTENSION_INSTALLED in mtdata: for flag in [ postgres._EXTENSION_TO_MOVE, postgres._EXTENSION_TO_UPGRADE ]: if flag in mtdata: toupgrade = True mode = 'upgrade' cret = None if toinstall or toupgrade: if __opts__['test']: ret['result'] = None if mode: ret['comment'] = 'Extension {0} is set to be {1}ed'.format( name, mode).replace('eed', 'ed') return ret cret = __salt__['postgres.create_extension']( name=name, if_not_exists=if_not_exists, schema=schema, ext_version=ext_version, from_version=from_version, **db_args) if cret: if mode.endswith('e'): suffix = 'd' else: suffix = 'ed' ret['comment'] = 'The extension {0} has been {1}{2}'.format(name, mode, suffix) ret['changes'][name] = '{0}{1}'.format(mode.capitalize(), suffix) elif cret is not None: ret['comment'] = 'Failed to {1} extension {0}'.format(name, mode) ret['result'] = False return ret
saltstack/salt
salt/auth/file.py
_get_file_auth_config
python
def _get_file_auth_config(): ''' Setup defaults and check configuration variables for auth backends ''' config = { 'filetype': 'text', 'hashtype': 'plaintext', 'field_separator': ':', 'username_field': 1, 'password_field': 2, } for opt in __opts__['external_auth'][__virtualname__]: if opt.startswith('^'): config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt] if 'filename' not in config: log.error('salt.auth.file: An authentication file must be specified ' 'via external_auth:file:^filename') return False if not os.path.exists(config['filename']): log.error('salt.auth.file: The configured external_auth:file:^filename (%s)' 'does not exist on the filesystem', config['filename']) return False config['username_field'] = int(config['username_field']) config['password_field'] = int(config['password_field']) return config
Setup defaults and check configuration variables for auth backends
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L116-L146
null
# -*- coding: utf-8 -*- ''' Provide authentication using local files .. versionadded:: 2018.3.0 The `file` auth module allows simple authentication via local files. Different filetypes are supported, including: 1. Text files, with passwords in plaintext or hashed 2. Apache-style htpasswd files 3. Apache-style htdigest files .. note:: The ``python-passlib`` library is required when using a ``^filetype`` of ``htpasswd`` or ``htdigest``. The simplest example is a plaintext file with usernames and passwords: .. code-block:: yaml external_auth: file: ^filename: /etc/insecure-user-list.txt gene: - .* dean: - test.* In this example the ``/etc/insecure-user-list.txt`` file would be formatted as so: .. code-block:: text dean:goneFishing gene:OceanMan ``^filename`` is the only required parameter. Any parameter that begins with a ``^`` is passed directly to the underlying file authentication function via ``kwargs``, with the leading ``^`` being stripped. The text file option is configurable to work with legacy formats: .. code-block:: yaml external_auth: file: ^filename: /etc/legacy_users.txt ^filetype: text ^hashtype: md5 ^username_field: 2 ^password_field: 3 ^field_separator: '|' trey: - .* This would authenticate users against a file of the following format: .. code-block:: text 46|trey|16a0034f90b06bf3c5982ed8ac41aab4 555|mike|b6e02a4d2cb2a6ef0669e79be6fd02e4 2001|page|14fce21db306a43d3b680da1a527847a 8888|jon|c4e94ba906578ccf494d71f45795c6cb .. note:: The :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function is used for comparing hashed passwords, so any algorithm supported by that function will work. There is also support for Apache-style ``htpasswd`` and ``htdigest`` files: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htusers ^filetype: htpasswd cory: - .* When using ``htdigest`` the ``^realm`` must be set: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htdigest ^filetype: htdigest ^realm: MySecureRealm cory: - .* ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import salt utils import salt.utils.files import salt.utils.versions log = logging.getLogger(__name__) __virtualname__ = 'file' def __virtual__(): return __virtualname__ def _text(username, password, **kwargs): ''' The text file function can authenticate plaintext and digest methods that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` function. ''' filename = kwargs['filename'] hashtype = kwargs['hashtype'] field_separator = kwargs['field_separator'] username_field = kwargs['username_field']-1 password_field = kwargs['password_field']-1 with salt.utils.files.fopen(filename, 'r') as pwfile: for line in pwfile.readlines(): fields = line.strip().split(field_separator) try: this_username = fields[username_field] except IndexError: log.error('salt.auth.file: username field (%s) does not exist ' 'in file %s', username_field, filename) return False try: this_password = fields[password_field] except IndexError: log.error('salt.auth.file: password field (%s) does not exist ' 'in file %s', password_field, filename) return False if this_username == username: if hashtype == 'plaintext': if this_password == password: return True else: # Exceptions for unknown hash types will be raised by hashutil.digest if this_password == __salt__['hashutil.digest'](password, hashtype): return True # Short circuit if we've already found the user but the password was wrong return False return False def _htpasswd(username, password, **kwargs): ''' Provide authentication via Apache-style htpasswd files ''' from passlib.apache import HtpasswdFile pwfile = HtpasswdFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, password) else: return pwfile.check_password(username, password) def _htdigest(username, password, **kwargs): ''' Provide authentication via Apache-style htdigest files ''' realm = kwargs.get('realm', None) if not realm: log.error('salt.auth.file: A ^realm must be defined in ' 'external_auth:file for htdigest filetype') return False from passlib.apache import HtdigestFile pwfile = HtdigestFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, realm, password) else: return pwfile.check_password(username, realm, password) def _htfile(username, password, **kwargs): ''' Gate function for _htpasswd and _htdigest authentication backends ''' filetype = kwargs.get('filetype', 'htpasswd').lower() try: import passlib kwargs['passlib_version'] = passlib.__version__ except ImportError: log.error('salt.auth.file: The python-passlib library is required ' 'for %s filetype', filetype) return False if filetype == 'htdigest': return _htdigest(username, password, **kwargs) else: return _htpasswd(username, password, **kwargs) FILETYPE_FUNCTION_MAP = { 'text': _text, 'htpasswd': _htfile, 'htdigest': _htfile } def auth(username, password): ''' File based authentication ^filename The path to the file to use for authentication. ^filetype The type of file: ``text``, ``htpasswd``, ``htdigest``. Default: ``text`` ^realm The realm required by htdigest authentication. .. note:: The following parameters are only used with the ``text`` filetype. ^hashtype The digest format of the password. Can be ``plaintext`` or any digest available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`. Default: ``plaintext`` ^field_separator The character to use as a delimiter between fields in a text file. Default: ``:`` ^username_field The numbered field in the text file that contains the username, with numbering beginning at 1 (one). Default: ``1`` ^password_field The numbered field in the text file that contains the password, with numbering beginning at 1 (one). Default: ``2`` ''' config = _get_file_auth_config() if not config: return False auth_function = FILETYPE_FUNCTION_MAP.get(config['filetype'], 'text') return auth_function(username, password, **config)
saltstack/salt
salt/auth/file.py
_text
python
def _text(username, password, **kwargs): ''' The text file function can authenticate plaintext and digest methods that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` function. ''' filename = kwargs['filename'] hashtype = kwargs['hashtype'] field_separator = kwargs['field_separator'] username_field = kwargs['username_field']-1 password_field = kwargs['password_field']-1 with salt.utils.files.fopen(filename, 'r') as pwfile: for line in pwfile.readlines(): fields = line.strip().split(field_separator) try: this_username = fields[username_field] except IndexError: log.error('salt.auth.file: username field (%s) does not exist ' 'in file %s', username_field, filename) return False try: this_password = fields[password_field] except IndexError: log.error('salt.auth.file: password field (%s) does not exist ' 'in file %s', password_field, filename) return False if this_username == username: if hashtype == 'plaintext': if this_password == password: return True else: # Exceptions for unknown hash types will be raised by hashutil.digest if this_password == __salt__['hashutil.digest'](password, hashtype): return True # Short circuit if we've already found the user but the password was wrong return False return False
The text file function can authenticate plaintext and digest methods that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` function.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L149-L190
null
# -*- coding: utf-8 -*- ''' Provide authentication using local files .. versionadded:: 2018.3.0 The `file` auth module allows simple authentication via local files. Different filetypes are supported, including: 1. Text files, with passwords in plaintext or hashed 2. Apache-style htpasswd files 3. Apache-style htdigest files .. note:: The ``python-passlib`` library is required when using a ``^filetype`` of ``htpasswd`` or ``htdigest``. The simplest example is a plaintext file with usernames and passwords: .. code-block:: yaml external_auth: file: ^filename: /etc/insecure-user-list.txt gene: - .* dean: - test.* In this example the ``/etc/insecure-user-list.txt`` file would be formatted as so: .. code-block:: text dean:goneFishing gene:OceanMan ``^filename`` is the only required parameter. Any parameter that begins with a ``^`` is passed directly to the underlying file authentication function via ``kwargs``, with the leading ``^`` being stripped. The text file option is configurable to work with legacy formats: .. code-block:: yaml external_auth: file: ^filename: /etc/legacy_users.txt ^filetype: text ^hashtype: md5 ^username_field: 2 ^password_field: 3 ^field_separator: '|' trey: - .* This would authenticate users against a file of the following format: .. code-block:: text 46|trey|16a0034f90b06bf3c5982ed8ac41aab4 555|mike|b6e02a4d2cb2a6ef0669e79be6fd02e4 2001|page|14fce21db306a43d3b680da1a527847a 8888|jon|c4e94ba906578ccf494d71f45795c6cb .. note:: The :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function is used for comparing hashed passwords, so any algorithm supported by that function will work. There is also support for Apache-style ``htpasswd`` and ``htdigest`` files: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htusers ^filetype: htpasswd cory: - .* When using ``htdigest`` the ``^realm`` must be set: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htdigest ^filetype: htdigest ^realm: MySecureRealm cory: - .* ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import salt utils import salt.utils.files import salt.utils.versions log = logging.getLogger(__name__) __virtualname__ = 'file' def __virtual__(): return __virtualname__ def _get_file_auth_config(): ''' Setup defaults and check configuration variables for auth backends ''' config = { 'filetype': 'text', 'hashtype': 'plaintext', 'field_separator': ':', 'username_field': 1, 'password_field': 2, } for opt in __opts__['external_auth'][__virtualname__]: if opt.startswith('^'): config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt] if 'filename' not in config: log.error('salt.auth.file: An authentication file must be specified ' 'via external_auth:file:^filename') return False if not os.path.exists(config['filename']): log.error('salt.auth.file: The configured external_auth:file:^filename (%s)' 'does not exist on the filesystem', config['filename']) return False config['username_field'] = int(config['username_field']) config['password_field'] = int(config['password_field']) return config def _htpasswd(username, password, **kwargs): ''' Provide authentication via Apache-style htpasswd files ''' from passlib.apache import HtpasswdFile pwfile = HtpasswdFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, password) else: return pwfile.check_password(username, password) def _htdigest(username, password, **kwargs): ''' Provide authentication via Apache-style htdigest files ''' realm = kwargs.get('realm', None) if not realm: log.error('salt.auth.file: A ^realm must be defined in ' 'external_auth:file for htdigest filetype') return False from passlib.apache import HtdigestFile pwfile = HtdigestFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, realm, password) else: return pwfile.check_password(username, realm, password) def _htfile(username, password, **kwargs): ''' Gate function for _htpasswd and _htdigest authentication backends ''' filetype = kwargs.get('filetype', 'htpasswd').lower() try: import passlib kwargs['passlib_version'] = passlib.__version__ except ImportError: log.error('salt.auth.file: The python-passlib library is required ' 'for %s filetype', filetype) return False if filetype == 'htdigest': return _htdigest(username, password, **kwargs) else: return _htpasswd(username, password, **kwargs) FILETYPE_FUNCTION_MAP = { 'text': _text, 'htpasswd': _htfile, 'htdigest': _htfile } def auth(username, password): ''' File based authentication ^filename The path to the file to use for authentication. ^filetype The type of file: ``text``, ``htpasswd``, ``htdigest``. Default: ``text`` ^realm The realm required by htdigest authentication. .. note:: The following parameters are only used with the ``text`` filetype. ^hashtype The digest format of the password. Can be ``plaintext`` or any digest available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`. Default: ``plaintext`` ^field_separator The character to use as a delimiter between fields in a text file. Default: ``:`` ^username_field The numbered field in the text file that contains the username, with numbering beginning at 1 (one). Default: ``1`` ^password_field The numbered field in the text file that contains the password, with numbering beginning at 1 (one). Default: ``2`` ''' config = _get_file_auth_config() if not config: return False auth_function = FILETYPE_FUNCTION_MAP.get(config['filetype'], 'text') return auth_function(username, password, **config)
saltstack/salt
salt/auth/file.py
_htpasswd
python
def _htpasswd(username, password, **kwargs): ''' Provide authentication via Apache-style htpasswd files ''' from passlib.apache import HtpasswdFile pwfile = HtpasswdFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, password) else: return pwfile.check_password(username, password)
Provide authentication via Apache-style htpasswd files
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L193-L206
null
# -*- coding: utf-8 -*- ''' Provide authentication using local files .. versionadded:: 2018.3.0 The `file` auth module allows simple authentication via local files. Different filetypes are supported, including: 1. Text files, with passwords in plaintext or hashed 2. Apache-style htpasswd files 3. Apache-style htdigest files .. note:: The ``python-passlib`` library is required when using a ``^filetype`` of ``htpasswd`` or ``htdigest``. The simplest example is a plaintext file with usernames and passwords: .. code-block:: yaml external_auth: file: ^filename: /etc/insecure-user-list.txt gene: - .* dean: - test.* In this example the ``/etc/insecure-user-list.txt`` file would be formatted as so: .. code-block:: text dean:goneFishing gene:OceanMan ``^filename`` is the only required parameter. Any parameter that begins with a ``^`` is passed directly to the underlying file authentication function via ``kwargs``, with the leading ``^`` being stripped. The text file option is configurable to work with legacy formats: .. code-block:: yaml external_auth: file: ^filename: /etc/legacy_users.txt ^filetype: text ^hashtype: md5 ^username_field: 2 ^password_field: 3 ^field_separator: '|' trey: - .* This would authenticate users against a file of the following format: .. code-block:: text 46|trey|16a0034f90b06bf3c5982ed8ac41aab4 555|mike|b6e02a4d2cb2a6ef0669e79be6fd02e4 2001|page|14fce21db306a43d3b680da1a527847a 8888|jon|c4e94ba906578ccf494d71f45795c6cb .. note:: The :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function is used for comparing hashed passwords, so any algorithm supported by that function will work. There is also support for Apache-style ``htpasswd`` and ``htdigest`` files: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htusers ^filetype: htpasswd cory: - .* When using ``htdigest`` the ``^realm`` must be set: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htdigest ^filetype: htdigest ^realm: MySecureRealm cory: - .* ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import salt utils import salt.utils.files import salt.utils.versions log = logging.getLogger(__name__) __virtualname__ = 'file' def __virtual__(): return __virtualname__ def _get_file_auth_config(): ''' Setup defaults and check configuration variables for auth backends ''' config = { 'filetype': 'text', 'hashtype': 'plaintext', 'field_separator': ':', 'username_field': 1, 'password_field': 2, } for opt in __opts__['external_auth'][__virtualname__]: if opt.startswith('^'): config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt] if 'filename' not in config: log.error('salt.auth.file: An authentication file must be specified ' 'via external_auth:file:^filename') return False if not os.path.exists(config['filename']): log.error('salt.auth.file: The configured external_auth:file:^filename (%s)' 'does not exist on the filesystem', config['filename']) return False config['username_field'] = int(config['username_field']) config['password_field'] = int(config['password_field']) return config def _text(username, password, **kwargs): ''' The text file function can authenticate plaintext and digest methods that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` function. ''' filename = kwargs['filename'] hashtype = kwargs['hashtype'] field_separator = kwargs['field_separator'] username_field = kwargs['username_field']-1 password_field = kwargs['password_field']-1 with salt.utils.files.fopen(filename, 'r') as pwfile: for line in pwfile.readlines(): fields = line.strip().split(field_separator) try: this_username = fields[username_field] except IndexError: log.error('salt.auth.file: username field (%s) does not exist ' 'in file %s', username_field, filename) return False try: this_password = fields[password_field] except IndexError: log.error('salt.auth.file: password field (%s) does not exist ' 'in file %s', password_field, filename) return False if this_username == username: if hashtype == 'plaintext': if this_password == password: return True else: # Exceptions for unknown hash types will be raised by hashutil.digest if this_password == __salt__['hashutil.digest'](password, hashtype): return True # Short circuit if we've already found the user but the password was wrong return False return False def _htdigest(username, password, **kwargs): ''' Provide authentication via Apache-style htdigest files ''' realm = kwargs.get('realm', None) if not realm: log.error('salt.auth.file: A ^realm must be defined in ' 'external_auth:file for htdigest filetype') return False from passlib.apache import HtdigestFile pwfile = HtdigestFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, realm, password) else: return pwfile.check_password(username, realm, password) def _htfile(username, password, **kwargs): ''' Gate function for _htpasswd and _htdigest authentication backends ''' filetype = kwargs.get('filetype', 'htpasswd').lower() try: import passlib kwargs['passlib_version'] = passlib.__version__ except ImportError: log.error('salt.auth.file: The python-passlib library is required ' 'for %s filetype', filetype) return False if filetype == 'htdigest': return _htdigest(username, password, **kwargs) else: return _htpasswd(username, password, **kwargs) FILETYPE_FUNCTION_MAP = { 'text': _text, 'htpasswd': _htfile, 'htdigest': _htfile } def auth(username, password): ''' File based authentication ^filename The path to the file to use for authentication. ^filetype The type of file: ``text``, ``htpasswd``, ``htdigest``. Default: ``text`` ^realm The realm required by htdigest authentication. .. note:: The following parameters are only used with the ``text`` filetype. ^hashtype The digest format of the password. Can be ``plaintext`` or any digest available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`. Default: ``plaintext`` ^field_separator The character to use as a delimiter between fields in a text file. Default: ``:`` ^username_field The numbered field in the text file that contains the username, with numbering beginning at 1 (one). Default: ``1`` ^password_field The numbered field in the text file that contains the password, with numbering beginning at 1 (one). Default: ``2`` ''' config = _get_file_auth_config() if not config: return False auth_function = FILETYPE_FUNCTION_MAP.get(config['filetype'], 'text') return auth_function(username, password, **config)
saltstack/salt
salt/auth/file.py
_htdigest
python
def _htdigest(username, password, **kwargs): ''' Provide authentication via Apache-style htdigest files ''' realm = kwargs.get('realm', None) if not realm: log.error('salt.auth.file: A ^realm must be defined in ' 'external_auth:file for htdigest filetype') return False from passlib.apache import HtdigestFile pwfile = HtdigestFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, realm, password) else: return pwfile.check_password(username, realm, password)
Provide authentication via Apache-style htdigest files
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L209-L228
null
# -*- coding: utf-8 -*- ''' Provide authentication using local files .. versionadded:: 2018.3.0 The `file` auth module allows simple authentication via local files. Different filetypes are supported, including: 1. Text files, with passwords in plaintext or hashed 2. Apache-style htpasswd files 3. Apache-style htdigest files .. note:: The ``python-passlib`` library is required when using a ``^filetype`` of ``htpasswd`` or ``htdigest``. The simplest example is a plaintext file with usernames and passwords: .. code-block:: yaml external_auth: file: ^filename: /etc/insecure-user-list.txt gene: - .* dean: - test.* In this example the ``/etc/insecure-user-list.txt`` file would be formatted as so: .. code-block:: text dean:goneFishing gene:OceanMan ``^filename`` is the only required parameter. Any parameter that begins with a ``^`` is passed directly to the underlying file authentication function via ``kwargs``, with the leading ``^`` being stripped. The text file option is configurable to work with legacy formats: .. code-block:: yaml external_auth: file: ^filename: /etc/legacy_users.txt ^filetype: text ^hashtype: md5 ^username_field: 2 ^password_field: 3 ^field_separator: '|' trey: - .* This would authenticate users against a file of the following format: .. code-block:: text 46|trey|16a0034f90b06bf3c5982ed8ac41aab4 555|mike|b6e02a4d2cb2a6ef0669e79be6fd02e4 2001|page|14fce21db306a43d3b680da1a527847a 8888|jon|c4e94ba906578ccf494d71f45795c6cb .. note:: The :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function is used for comparing hashed passwords, so any algorithm supported by that function will work. There is also support for Apache-style ``htpasswd`` and ``htdigest`` files: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htusers ^filetype: htpasswd cory: - .* When using ``htdigest`` the ``^realm`` must be set: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htdigest ^filetype: htdigest ^realm: MySecureRealm cory: - .* ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import salt utils import salt.utils.files import salt.utils.versions log = logging.getLogger(__name__) __virtualname__ = 'file' def __virtual__(): return __virtualname__ def _get_file_auth_config(): ''' Setup defaults and check configuration variables for auth backends ''' config = { 'filetype': 'text', 'hashtype': 'plaintext', 'field_separator': ':', 'username_field': 1, 'password_field': 2, } for opt in __opts__['external_auth'][__virtualname__]: if opt.startswith('^'): config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt] if 'filename' not in config: log.error('salt.auth.file: An authentication file must be specified ' 'via external_auth:file:^filename') return False if not os.path.exists(config['filename']): log.error('salt.auth.file: The configured external_auth:file:^filename (%s)' 'does not exist on the filesystem', config['filename']) return False config['username_field'] = int(config['username_field']) config['password_field'] = int(config['password_field']) return config def _text(username, password, **kwargs): ''' The text file function can authenticate plaintext and digest methods that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` function. ''' filename = kwargs['filename'] hashtype = kwargs['hashtype'] field_separator = kwargs['field_separator'] username_field = kwargs['username_field']-1 password_field = kwargs['password_field']-1 with salt.utils.files.fopen(filename, 'r') as pwfile: for line in pwfile.readlines(): fields = line.strip().split(field_separator) try: this_username = fields[username_field] except IndexError: log.error('salt.auth.file: username field (%s) does not exist ' 'in file %s', username_field, filename) return False try: this_password = fields[password_field] except IndexError: log.error('salt.auth.file: password field (%s) does not exist ' 'in file %s', password_field, filename) return False if this_username == username: if hashtype == 'plaintext': if this_password == password: return True else: # Exceptions for unknown hash types will be raised by hashutil.digest if this_password == __salt__['hashutil.digest'](password, hashtype): return True # Short circuit if we've already found the user but the password was wrong return False return False def _htpasswd(username, password, **kwargs): ''' Provide authentication via Apache-style htpasswd files ''' from passlib.apache import HtpasswdFile pwfile = HtpasswdFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, password) else: return pwfile.check_password(username, password) def _htfile(username, password, **kwargs): ''' Gate function for _htpasswd and _htdigest authentication backends ''' filetype = kwargs.get('filetype', 'htpasswd').lower() try: import passlib kwargs['passlib_version'] = passlib.__version__ except ImportError: log.error('salt.auth.file: The python-passlib library is required ' 'for %s filetype', filetype) return False if filetype == 'htdigest': return _htdigest(username, password, **kwargs) else: return _htpasswd(username, password, **kwargs) FILETYPE_FUNCTION_MAP = { 'text': _text, 'htpasswd': _htfile, 'htdigest': _htfile } def auth(username, password): ''' File based authentication ^filename The path to the file to use for authentication. ^filetype The type of file: ``text``, ``htpasswd``, ``htdigest``. Default: ``text`` ^realm The realm required by htdigest authentication. .. note:: The following parameters are only used with the ``text`` filetype. ^hashtype The digest format of the password. Can be ``plaintext`` or any digest available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`. Default: ``plaintext`` ^field_separator The character to use as a delimiter between fields in a text file. Default: ``:`` ^username_field The numbered field in the text file that contains the username, with numbering beginning at 1 (one). Default: ``1`` ^password_field The numbered field in the text file that contains the password, with numbering beginning at 1 (one). Default: ``2`` ''' config = _get_file_auth_config() if not config: return False auth_function = FILETYPE_FUNCTION_MAP.get(config['filetype'], 'text') return auth_function(username, password, **config)
saltstack/salt
salt/auth/file.py
_htfile
python
def _htfile(username, password, **kwargs): ''' Gate function for _htpasswd and _htdigest authentication backends ''' filetype = kwargs.get('filetype', 'htpasswd').lower() try: import passlib kwargs['passlib_version'] = passlib.__version__ except ImportError: log.error('salt.auth.file: The python-passlib library is required ' 'for %s filetype', filetype) return False if filetype == 'htdigest': return _htdigest(username, password, **kwargs) else: return _htpasswd(username, password, **kwargs)
Gate function for _htpasswd and _htdigest authentication backends
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L231-L249
null
# -*- coding: utf-8 -*- ''' Provide authentication using local files .. versionadded:: 2018.3.0 The `file` auth module allows simple authentication via local files. Different filetypes are supported, including: 1. Text files, with passwords in plaintext or hashed 2. Apache-style htpasswd files 3. Apache-style htdigest files .. note:: The ``python-passlib`` library is required when using a ``^filetype`` of ``htpasswd`` or ``htdigest``. The simplest example is a plaintext file with usernames and passwords: .. code-block:: yaml external_auth: file: ^filename: /etc/insecure-user-list.txt gene: - .* dean: - test.* In this example the ``/etc/insecure-user-list.txt`` file would be formatted as so: .. code-block:: text dean:goneFishing gene:OceanMan ``^filename`` is the only required parameter. Any parameter that begins with a ``^`` is passed directly to the underlying file authentication function via ``kwargs``, with the leading ``^`` being stripped. The text file option is configurable to work with legacy formats: .. code-block:: yaml external_auth: file: ^filename: /etc/legacy_users.txt ^filetype: text ^hashtype: md5 ^username_field: 2 ^password_field: 3 ^field_separator: '|' trey: - .* This would authenticate users against a file of the following format: .. code-block:: text 46|trey|16a0034f90b06bf3c5982ed8ac41aab4 555|mike|b6e02a4d2cb2a6ef0669e79be6fd02e4 2001|page|14fce21db306a43d3b680da1a527847a 8888|jon|c4e94ba906578ccf494d71f45795c6cb .. note:: The :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function is used for comparing hashed passwords, so any algorithm supported by that function will work. There is also support for Apache-style ``htpasswd`` and ``htdigest`` files: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htusers ^filetype: htpasswd cory: - .* When using ``htdigest`` the ``^realm`` must be set: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htdigest ^filetype: htdigest ^realm: MySecureRealm cory: - .* ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import salt utils import salt.utils.files import salt.utils.versions log = logging.getLogger(__name__) __virtualname__ = 'file' def __virtual__(): return __virtualname__ def _get_file_auth_config(): ''' Setup defaults and check configuration variables for auth backends ''' config = { 'filetype': 'text', 'hashtype': 'plaintext', 'field_separator': ':', 'username_field': 1, 'password_field': 2, } for opt in __opts__['external_auth'][__virtualname__]: if opt.startswith('^'): config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt] if 'filename' not in config: log.error('salt.auth.file: An authentication file must be specified ' 'via external_auth:file:^filename') return False if not os.path.exists(config['filename']): log.error('salt.auth.file: The configured external_auth:file:^filename (%s)' 'does not exist on the filesystem', config['filename']) return False config['username_field'] = int(config['username_field']) config['password_field'] = int(config['password_field']) return config def _text(username, password, **kwargs): ''' The text file function can authenticate plaintext and digest methods that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` function. ''' filename = kwargs['filename'] hashtype = kwargs['hashtype'] field_separator = kwargs['field_separator'] username_field = kwargs['username_field']-1 password_field = kwargs['password_field']-1 with salt.utils.files.fopen(filename, 'r') as pwfile: for line in pwfile.readlines(): fields = line.strip().split(field_separator) try: this_username = fields[username_field] except IndexError: log.error('salt.auth.file: username field (%s) does not exist ' 'in file %s', username_field, filename) return False try: this_password = fields[password_field] except IndexError: log.error('salt.auth.file: password field (%s) does not exist ' 'in file %s', password_field, filename) return False if this_username == username: if hashtype == 'plaintext': if this_password == password: return True else: # Exceptions for unknown hash types will be raised by hashutil.digest if this_password == __salt__['hashutil.digest'](password, hashtype): return True # Short circuit if we've already found the user but the password was wrong return False return False def _htpasswd(username, password, **kwargs): ''' Provide authentication via Apache-style htpasswd files ''' from passlib.apache import HtpasswdFile pwfile = HtpasswdFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, password) else: return pwfile.check_password(username, password) def _htdigest(username, password, **kwargs): ''' Provide authentication via Apache-style htdigest files ''' realm = kwargs.get('realm', None) if not realm: log.error('salt.auth.file: A ^realm must be defined in ' 'external_auth:file for htdigest filetype') return False from passlib.apache import HtdigestFile pwfile = HtdigestFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, realm, password) else: return pwfile.check_password(username, realm, password) FILETYPE_FUNCTION_MAP = { 'text': _text, 'htpasswd': _htfile, 'htdigest': _htfile } def auth(username, password): ''' File based authentication ^filename The path to the file to use for authentication. ^filetype The type of file: ``text``, ``htpasswd``, ``htdigest``. Default: ``text`` ^realm The realm required by htdigest authentication. .. note:: The following parameters are only used with the ``text`` filetype. ^hashtype The digest format of the password. Can be ``plaintext`` or any digest available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`. Default: ``plaintext`` ^field_separator The character to use as a delimiter between fields in a text file. Default: ``:`` ^username_field The numbered field in the text file that contains the username, with numbering beginning at 1 (one). Default: ``1`` ^password_field The numbered field in the text file that contains the password, with numbering beginning at 1 (one). Default: ``2`` ''' config = _get_file_auth_config() if not config: return False auth_function = FILETYPE_FUNCTION_MAP.get(config['filetype'], 'text') return auth_function(username, password, **config)
saltstack/salt
salt/auth/file.py
auth
python
def auth(username, password): ''' File based authentication ^filename The path to the file to use for authentication. ^filetype The type of file: ``text``, ``htpasswd``, ``htdigest``. Default: ``text`` ^realm The realm required by htdigest authentication. .. note:: The following parameters are only used with the ``text`` filetype. ^hashtype The digest format of the password. Can be ``plaintext`` or any digest available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`. Default: ``plaintext`` ^field_separator The character to use as a delimiter between fields in a text file. Default: ``:`` ^username_field The numbered field in the text file that contains the username, with numbering beginning at 1 (one). Default: ``1`` ^password_field The numbered field in the text file that contains the password, with numbering beginning at 1 (one). Default: ``2`` ''' config = _get_file_auth_config() if not config: return False auth_function = FILETYPE_FUNCTION_MAP.get(config['filetype'], 'text') return auth_function(username, password, **config)
File based authentication ^filename The path to the file to use for authentication. ^filetype The type of file: ``text``, ``htpasswd``, ``htdigest``. Default: ``text`` ^realm The realm required by htdigest authentication. .. note:: The following parameters are only used with the ``text`` filetype. ^hashtype The digest format of the password. Can be ``plaintext`` or any digest available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`. Default: ``plaintext`` ^field_separator The character to use as a delimiter between fields in a text file. Default: ``:`` ^username_field The numbered field in the text file that contains the username, with numbering beginning at 1 (one). Default: ``1`` ^password_field The numbered field in the text file that contains the password, with numbering beginning at 1 (one). Default: ``2``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L259-L308
[ "def _get_file_auth_config():\n '''\n Setup defaults and check configuration variables for auth backends\n '''\n\n config = {\n 'filetype': 'text',\n 'hashtype': 'plaintext',\n 'field_separator': ':',\n 'username_field': 1,\n 'password_field': 2,\n }\n\n for opt in __opts__['external_auth'][__virtualname__]:\n if opt.startswith('^'):\n config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt]\n\n if 'filename' not in config:\n log.error('salt.auth.file: An authentication file must be specified '\n 'via external_auth:file:^filename')\n return False\n\n if not os.path.exists(config['filename']):\n log.error('salt.auth.file: The configured external_auth:file:^filename (%s)'\n 'does not exist on the filesystem', config['filename'])\n return False\n\n config['username_field'] = int(config['username_field'])\n config['password_field'] = int(config['password_field'])\n\n return config\n" ]
# -*- coding: utf-8 -*- ''' Provide authentication using local files .. versionadded:: 2018.3.0 The `file` auth module allows simple authentication via local files. Different filetypes are supported, including: 1. Text files, with passwords in plaintext or hashed 2. Apache-style htpasswd files 3. Apache-style htdigest files .. note:: The ``python-passlib`` library is required when using a ``^filetype`` of ``htpasswd`` or ``htdigest``. The simplest example is a plaintext file with usernames and passwords: .. code-block:: yaml external_auth: file: ^filename: /etc/insecure-user-list.txt gene: - .* dean: - test.* In this example the ``/etc/insecure-user-list.txt`` file would be formatted as so: .. code-block:: text dean:goneFishing gene:OceanMan ``^filename`` is the only required parameter. Any parameter that begins with a ``^`` is passed directly to the underlying file authentication function via ``kwargs``, with the leading ``^`` being stripped. The text file option is configurable to work with legacy formats: .. code-block:: yaml external_auth: file: ^filename: /etc/legacy_users.txt ^filetype: text ^hashtype: md5 ^username_field: 2 ^password_field: 3 ^field_separator: '|' trey: - .* This would authenticate users against a file of the following format: .. code-block:: text 46|trey|16a0034f90b06bf3c5982ed8ac41aab4 555|mike|b6e02a4d2cb2a6ef0669e79be6fd02e4 2001|page|14fce21db306a43d3b680da1a527847a 8888|jon|c4e94ba906578ccf494d71f45795c6cb .. note:: The :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function is used for comparing hashed passwords, so any algorithm supported by that function will work. There is also support for Apache-style ``htpasswd`` and ``htdigest`` files: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htusers ^filetype: htpasswd cory: - .* When using ``htdigest`` the ``^realm`` must be set: .. code-block:: yaml external_auth: file: ^filename: /var/www/html/.htdigest ^filetype: htdigest ^realm: MySecureRealm cory: - .* ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import salt utils import salt.utils.files import salt.utils.versions log = logging.getLogger(__name__) __virtualname__ = 'file' def __virtual__(): return __virtualname__ def _get_file_auth_config(): ''' Setup defaults and check configuration variables for auth backends ''' config = { 'filetype': 'text', 'hashtype': 'plaintext', 'field_separator': ':', 'username_field': 1, 'password_field': 2, } for opt in __opts__['external_auth'][__virtualname__]: if opt.startswith('^'): config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt] if 'filename' not in config: log.error('salt.auth.file: An authentication file must be specified ' 'via external_auth:file:^filename') return False if not os.path.exists(config['filename']): log.error('salt.auth.file: The configured external_auth:file:^filename (%s)' 'does not exist on the filesystem', config['filename']) return False config['username_field'] = int(config['username_field']) config['password_field'] = int(config['password_field']) return config def _text(username, password, **kwargs): ''' The text file function can authenticate plaintext and digest methods that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` function. ''' filename = kwargs['filename'] hashtype = kwargs['hashtype'] field_separator = kwargs['field_separator'] username_field = kwargs['username_field']-1 password_field = kwargs['password_field']-1 with salt.utils.files.fopen(filename, 'r') as pwfile: for line in pwfile.readlines(): fields = line.strip().split(field_separator) try: this_username = fields[username_field] except IndexError: log.error('salt.auth.file: username field (%s) does not exist ' 'in file %s', username_field, filename) return False try: this_password = fields[password_field] except IndexError: log.error('salt.auth.file: password field (%s) does not exist ' 'in file %s', password_field, filename) return False if this_username == username: if hashtype == 'plaintext': if this_password == password: return True else: # Exceptions for unknown hash types will be raised by hashutil.digest if this_password == __salt__['hashutil.digest'](password, hashtype): return True # Short circuit if we've already found the user but the password was wrong return False return False def _htpasswd(username, password, **kwargs): ''' Provide authentication via Apache-style htpasswd files ''' from passlib.apache import HtpasswdFile pwfile = HtpasswdFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, password) else: return pwfile.check_password(username, password) def _htdigest(username, password, **kwargs): ''' Provide authentication via Apache-style htdigest files ''' realm = kwargs.get('realm', None) if not realm: log.error('salt.auth.file: A ^realm must be defined in ' 'external_auth:file for htdigest filetype') return False from passlib.apache import HtdigestFile pwfile = HtdigestFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0: return pwfile.verify(username, realm, password) else: return pwfile.check_password(username, realm, password) def _htfile(username, password, **kwargs): ''' Gate function for _htpasswd and _htdigest authentication backends ''' filetype = kwargs.get('filetype', 'htpasswd').lower() try: import passlib kwargs['passlib_version'] = passlib.__version__ except ImportError: log.error('salt.auth.file: The python-passlib library is required ' 'for %s filetype', filetype) return False if filetype == 'htdigest': return _htdigest(username, password, **kwargs) else: return _htpasswd(username, password, **kwargs) FILETYPE_FUNCTION_MAP = { 'text': _text, 'htpasswd': _htfile, 'htdigest': _htfile }
saltstack/salt
salt/states/openvswitch_bridge.py
present
python
def present(name, parent=None, vlan=None): ''' Ensures that the named bridge exists, eventually creates it. Args: name: The name of the bridge. parent: The name of the parent bridge (if the bridge shall be created as a fake bridge). If specified, vlan must also be specified. vlan: The VLAN ID of the bridge (if the bridge shall be created as a fake bridge). If specified, parent must also be specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Comment and change messages comment_bridge_created = 'Bridge {0} created.'.format(name) comment_bridge_notcreated = 'Unable to create bridge: {0}.'.format(name) comment_bridge_exists = 'Bridge {0} already exists.'.format(name) comment_bridge_mismatch = ('Bridge {0} already exists, but has a different' ' parent or VLAN ID.').format(name) changes_bridge_created = {name: {'old': 'Bridge {0} does not exist.'.format(name), 'new': 'Bridge {0} created'.format(name), } } bridge_exists = __salt__['openvswitch.bridge_exists'](name) if bridge_exists: current_parent = __salt__['openvswitch.bridge_to_parent'](name) if current_parent == name: current_parent = None current_vlan = __salt__['openvswitch.bridge_to_vlan'](name) if current_vlan == 0: current_vlan = None # Dry run, test=true mode if __opts__['test']: if bridge_exists: if current_parent == parent and current_vlan == vlan: ret['result'] = True ret['comment'] = comment_bridge_exists else: ret['result'] = False ret['comment'] = comment_bridge_mismatch else: ret['result'] = None ret['comment'] = comment_bridge_created return ret if bridge_exists: if current_parent == parent and current_vlan == vlan: ret['result'] = True ret['comment'] = comment_bridge_exists else: ret['result'] = False ret['comment'] = comment_bridge_mismatch else: bridge_create = __salt__['openvswitch.bridge_create']( name, parent=parent, vlan=vlan) if bridge_create: ret['result'] = True ret['comment'] = comment_bridge_created ret['changes'] = changes_bridge_created else: ret['result'] = False ret['comment'] = comment_bridge_notcreated return ret
Ensures that the named bridge exists, eventually creates it. Args: name: The name of the bridge. parent: The name of the parent bridge (if the bridge shall be created as a fake bridge). If specified, vlan must also be specified. vlan: The VLAN ID of the bridge (if the bridge shall be created as a fake bridge). If specified, parent must also be specified.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/openvswitch_bridge.py#L17-L84
null
# -*- coding: utf-8 -*- ''' Management of Open vSwitch bridges. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only make these states available if Open vSwitch module is available. ''' return 'openvswitch.bridge_create' in __salt__ def absent(name): ''' Ensures that the named bridge does not exist, eventually deletes it. Args: name: The name of the bridge. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Comment and change messages comment_bridge_deleted = 'Bridge {0} deleted.'.format(name) comment_bridge_notdeleted = 'Unable to delete bridge: {0}.'.format(name) comment_bridge_notexists = 'Bridge {0} does not exist.'.format(name) changes_bridge_deleted = {name: {'old': 'Bridge {0} exists.'.format(name), 'new': 'Bridge {0} deleted.'.format(name), } } bridge_exists = __salt__['openvswitch.bridge_exists'](name) # Dry run, test=true mode if __opts__['test']: if not bridge_exists: ret['result'] = True ret['comment'] = comment_bridge_notexists else: ret['result'] = None ret['comment'] = comment_bridge_deleted return ret if not bridge_exists: ret['result'] = True ret['comment'] = comment_bridge_notexists else: bridge_delete = __salt__['openvswitch.bridge_delete'](name) if bridge_delete: ret['result'] = True ret['comment'] = comment_bridge_deleted ret['changes'] = changes_bridge_deleted else: ret['result'] = False ret['comment'] = comment_bridge_notdeleted return ret
saltstack/salt
salt/states/openvswitch_bridge.py
absent
python
def absent(name): ''' Ensures that the named bridge does not exist, eventually deletes it. Args: name: The name of the bridge. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Comment and change messages comment_bridge_deleted = 'Bridge {0} deleted.'.format(name) comment_bridge_notdeleted = 'Unable to delete bridge: {0}.'.format(name) comment_bridge_notexists = 'Bridge {0} does not exist.'.format(name) changes_bridge_deleted = {name: {'old': 'Bridge {0} exists.'.format(name), 'new': 'Bridge {0} deleted.'.format(name), } } bridge_exists = __salt__['openvswitch.bridge_exists'](name) # Dry run, test=true mode if __opts__['test']: if not bridge_exists: ret['result'] = True ret['comment'] = comment_bridge_notexists else: ret['result'] = None ret['comment'] = comment_bridge_deleted return ret if not bridge_exists: ret['result'] = True ret['comment'] = comment_bridge_notexists else: bridge_delete = __salt__['openvswitch.bridge_delete'](name) if bridge_delete: ret['result'] = True ret['comment'] = comment_bridge_deleted ret['changes'] = changes_bridge_deleted else: ret['result'] = False ret['comment'] = comment_bridge_notdeleted return ret
Ensures that the named bridge does not exist, eventually deletes it. Args: name: The name of the bridge.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/openvswitch_bridge.py#L87-L133
null
# -*- coding: utf-8 -*- ''' Management of Open vSwitch bridges. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only make these states available if Open vSwitch module is available. ''' return 'openvswitch.bridge_create' in __salt__ def present(name, parent=None, vlan=None): ''' Ensures that the named bridge exists, eventually creates it. Args: name: The name of the bridge. parent: The name of the parent bridge (if the bridge shall be created as a fake bridge). If specified, vlan must also be specified. vlan: The VLAN ID of the bridge (if the bridge shall be created as a fake bridge). If specified, parent must also be specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Comment and change messages comment_bridge_created = 'Bridge {0} created.'.format(name) comment_bridge_notcreated = 'Unable to create bridge: {0}.'.format(name) comment_bridge_exists = 'Bridge {0} already exists.'.format(name) comment_bridge_mismatch = ('Bridge {0} already exists, but has a different' ' parent or VLAN ID.').format(name) changes_bridge_created = {name: {'old': 'Bridge {0} does not exist.'.format(name), 'new': 'Bridge {0} created'.format(name), } } bridge_exists = __salt__['openvswitch.bridge_exists'](name) if bridge_exists: current_parent = __salt__['openvswitch.bridge_to_parent'](name) if current_parent == name: current_parent = None current_vlan = __salt__['openvswitch.bridge_to_vlan'](name) if current_vlan == 0: current_vlan = None # Dry run, test=true mode if __opts__['test']: if bridge_exists: if current_parent == parent and current_vlan == vlan: ret['result'] = True ret['comment'] = comment_bridge_exists else: ret['result'] = False ret['comment'] = comment_bridge_mismatch else: ret['result'] = None ret['comment'] = comment_bridge_created return ret if bridge_exists: if current_parent == parent and current_vlan == vlan: ret['result'] = True ret['comment'] = comment_bridge_exists else: ret['result'] = False ret['comment'] = comment_bridge_mismatch else: bridge_create = __salt__['openvswitch.bridge_create']( name, parent=parent, vlan=vlan) if bridge_create: ret['result'] = True ret['comment'] = comment_bridge_created ret['changes'] = changes_bridge_created else: ret['result'] = False ret['comment'] = comment_bridge_notcreated return ret
saltstack/salt
salt/pillar/cmd_yamlex.py
ext_pillar
python
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 command): ''' Execute a command and read the output as YAMLEX ''' try: command = command.replace('%s', minion_id) return deserialize(__salt__['cmd.run']('{0}'.format(command))) except Exception: log.critical('YAML data from %s failed to parse', command) return {}
Execute a command and read the output as YAMLEX
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/cmd_yamlex.py#L19-L30
[ "def deserialize(stream_or_string, **options):\n '''\n Deserialize any string of stream like object into a Python data structure.\n\n :param stream_or_string: stream or string to deserialize.\n :param options: options given to lower yaml module.\n '''\n\n options.setdefault('Loader', Loader)\n try:\n return yaml.load(stream_or_string, **options)\n except ScannerError as error:\n log.exception('Error encountered while deserializing')\n err_type = ERROR_MAP.get(error.problem, 'Unknown yaml render error')\n line_num = error.problem_mark.line + 1\n raise DeserializationError(err_type,\n line_num,\n error.problem_mark.buffer)\n except ConstructorError as error:\n log.exception('Error encountered while deserializing')\n raise DeserializationError(error)\n except Exception as error:\n log.exception('Error encountered while deserializing')\n raise DeserializationError(error)\n" ]
# -*- coding: utf-8 -*- ''' Execute a command and read the output as YAMLEX. The YAMLEX data is then directly overlaid onto the minion's Pillar data ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs from salt.serializers.yamlex import deserialize # Set up logging log = logging.getLogger(__name__)
saltstack/salt
salt/states/kubernetes.py
deployment_absent
python
def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret
Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L111-L149
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
deployment_present
python
def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret
Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L152-L244
[ "def _error(ret, err_msg):\n '''\n Helper function to propagate errors to\n the end user.\n '''\n ret['result'] = False\n ret['comment'] = err_msg\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
service_present
python
def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret
Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L247-L340
[ "def _error(ret, err_msg):\n '''\n Helper function to propagate errors to\n the end user.\n '''\n ret['result'] = False\n ret['comment'] = err_msg\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
service_absent
python
def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret
Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L343-L381
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
namespace_absent
python
def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret
Ensures that the named namespace is absent. name The name of the namespace
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L384-L431
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
namespace_present
python
def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret
Ensures that the named namespace is present. name The name of the namespace.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L434-L464
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
secret_absent
python
def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret
Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L467-L505
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
secret_present
python
def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret
Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L508-L592
[ "def _error(ret, err_msg):\n '''\n Helper function to propagate errors to\n the end user.\n '''\n ret['result'] = False\n ret['comment'] = err_msg\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
configmap_absent
python
def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret
Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L595-L634
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
configmap_present
python
def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret
Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L637-L717
[ "def _error(ret, err_msg):\n '''\n Helper function to propagate errors to\n the end user.\n '''\n ret['result'] = False\n ret['comment'] = err_msg\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
pod_absent
python
def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret
Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L720-L761
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
pod_present
python
def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret
Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L764-L850
[ "def _error(ret, err_msg):\n '''\n Helper function to propagate errors to\n the end user.\n '''\n ret['result'] = False\n ret['comment'] = err_msg\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
node_label_absent
python
def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret
Ensures that the named label is absent from the node. name The name of the label node The name of the node
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L853-L892
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
node_label_folder_absent
python
def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret
Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L895-L946
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
saltstack/salt
salt/states/kubernetes.py
node_label_present
python
def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be set' return ret __salt__['kubernetes.node_add_label'](label_name=name, label_value=value, node_name=node, **kwargs) elif labels[name] == value: ret['result'] = True ret['comment'] = 'The label is already set and has the specified value' return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The label is going to be updated' return ret ret['comment'] = 'The label is already set, changing the value' __salt__['kubernetes.node_add_label']( node_name=node, label_name=name, label_value=value, **kwargs) old_labels = copy.copy(labels) labels[name] = value ret['changes']['{0}.{1}'.format(node, name)] = { 'old': old_labels, 'new': labels} ret['result'] = True return ret
Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node Node to change.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L949-L1009
null
# -*- coding: utf-8 -*- ''' Manage kubernetes resources as salt states ========================================== NOTE: This module requires the proper pillar values set. See salt.modules.kubernetesmod for more information. .. warning:: Configuration options will change in 2019.2.0. The kubernetes module is used to manage different kubernetes resources. .. code-block:: yaml my-nginx: kubernetes.deployment_present: - namespace: default metadata: app: frontend spec: replicas: 1 template: metadata: labels: run: my-nginx spec: containers: - name: my-nginx image: nginx ports: - containerPort: 80 my-mariadb: kubernetes.deployment_absent: - namespace: default # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format redis-master-deployment: kubernetes.deployment_present: - name: redis-master - source: salt://k8s/redis-master-deployment.yml require: - pip: kubernetes-python-module # kubernetes service as specified inside of # a file containing the definition of the the # service using the official kubernetes format redis-master-service: kubernetes.service_present: - name: redis-master - source: salt://k8s/redis-master-service.yml require: - kubernetes.deployment_present: redis-master # kubernetes deployment as specified inside of # a file containing the definition of the the # deployment using the official kubernetes format # plus some jinja directives nginx-source-template: kubernetes.deployment_present: - source: salt://k8s/nginx.yml.jinja - template: jinja require: - pip: kubernetes-python-module # Kubernetes secret k8s-secret: kubernetes.secret_present: - name: top-secret data: key1: value1 key2: value2 key3: value3 .. versionadded: 2017.7.0 ''' from __future__ import absolute_import import copy import logging # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the kubernetes module is available in __salt__ ''' return 'kubernetes.ping' in __salt__ def _error(ret, err_msg): ''' Helper function to propagate errors to the end user. ''' ret['result'] = False ret['comment'] = err_msg return ret def deployment_absent(name, namespace='default', **kwargs): ''' Ensures that the named deployment is absent from the given namespace. name The name of the deployment namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The deployment does not exist' return ret if __opts__['test']: ret['comment'] = 'The deployment is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.deployment': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def deployment_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named deployment is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the deployment. namespace The namespace holding the deployment. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the deployment object. spec The spec of the deployment object. source A file containing the definition of the deployment (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs) if deployment is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The deployment is going to be created' return ret res = __salt__['kubernetes.create_deployment'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the deployment') ret['comment'] = 'The deployment is already present. Forcing recreation' res = __salt__['kubernetes.replace_deployment']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named service is present inside of the specified namespace with the given metadata and spec. If the deployment exists it will be replaced. name The name of the service. namespace The namespace holding the service. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the service object. spec The spec of the service object. source A file containing the definition of the service (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The service is going to be created' return ret res = __salt__['kubernetes.create_service'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The service is already present. Forcing recreation' res = __salt__['kubernetes.replace_service']( name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, old_service=service, saltenv=__env__, **kwargs) ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def service_absent(name, namespace='default', **kwargs): ''' Ensures that the named service is absent from the given namespace. name The name of the service namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} service = __salt__['kubernetes.show_service'](name, namespace, **kwargs) if service is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The service does not exist' return ret if __opts__['test']: ret['comment'] = 'The service is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs) if res['code'] == 200: ret['result'] = True ret['changes'] = { 'kubernetes.service': { 'new': 'absent', 'old': 'present'}} ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace does not exist' return ret if __opts__['test']: ret['comment'] = 'The namespace is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_namespace'](name, **kwargs) if ( res['code'] == 200 or ( isinstance(res['status'], six.string_types) and 'Terminating' in res['status'] ) or ( isinstance(res['status'], dict) and res['status']['phase'] == 'Terminating' )): ret['result'] = True ret['changes'] = { 'kubernetes.namespace': { 'new': 'absent', 'old': 'present'}} if res['message']: ret['comment'] = res['message'] else: ret['comment'] = 'Terminating' else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def namespace_present(name, **kwargs): ''' Ensures that the named namespace is present. name The name of the namespace. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwargs) if namespace is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The namespace is going to be created' return ret res = __salt__['kubernetes.create_namespace'](name, **kwargs) ret['result'] = True ret['changes']['namespace'] = { 'old': {}, 'new': res} else: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The namespace already exists' return ret def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The secret does not exist' return ret if __opts__['test']: ret['comment'] = 'The secret is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_secret'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a secret # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.secret': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Secret deleted' return ret def secret_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secret. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the secrets. source A file containing the data of the secret in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs) if secret is None: if data is None: data = {} if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be created' return ret res = __salt__['kubernetes.create_secret'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The secret is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The secret is already present. Forcing recreation' res = __salt__['kubernetes.replace_secret']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { # Omit values from the return. They are unencrypted # and can contain sensitive data. 'data': list(res['data']) } ret['result'] = True return ret def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The configmap does not exist' return ret if __opts__['test']: ret['comment'] = 'The configmap is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.delete_configmap'](name, namespace, **kwargs) # As for kubernetes 1.6.4 doesn't set a code when deleting a configmap # The kubernetes module will raise an exception if the kubernetes # server will return an error ret['result'] = True ret['changes'] = { 'kubernetes.configmap': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'ConfigMap deleted' return ret def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. name The name of the configmap. namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is specified. data The dictionary holding the configmaps. source A file containing the data of the configmap in plain format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if data and source: return _error( ret, '\'source\' cannot be used in combination with \'data\'' ) elif data is None: data = {} configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs) if configmap is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be created' return ret res = __salt__['kubernetes.create_configmap'](name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None ret['comment'] = 'The configmap is going to be replaced' return ret # TODO: improve checks # pylint: disable=fixme log.info('Forcing the recreation of the service') ret['comment'] = 'The configmap is already present. Forcing recreation' res = __salt__['kubernetes.replace_configmap']( name=name, namespace=namespace, data=data, source=source, template=template, saltenv=__env__, **kwargs) ret['changes'] = { 'data': res['data'] } ret['result'] = True return ret def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The pod does not exist' return ret if __opts__['test']: ret['comment'] = 'The pod is going to be deleted' ret['result'] = None return ret res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs) if res['code'] == 200 or res['code'] is None: ret['result'] = True ret['changes'] = { 'kubernetes.pod': { 'new': 'absent', 'old': 'present'}} if res['code'] is None: ret['comment'] = 'In progress' else: ret['comment'] = res['message'] else: ret['comment'] = 'Something went wrong, response: {0}'.format(res) return ret def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced. name The name of the pod. namespace The namespace holding the pod. The 'default' one is going to be used unless a different one is specified. metadata The metadata of the pod object. spec The spec of the pod object. source A file containing the definition of the pod (metadata and spec) in the official kubernetes format. template Template engine to be used to render the source file. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if (metadata or spec) and source: return _error( ret, '\'source\' cannot be used in combination with \'metadata\' or ' '\'spec\'' ) if metadata is None: metadata = {} if spec is None: spec = {} pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs) if pod is None: if __opts__['test']: ret['result'] = None ret['comment'] = 'The pod is going to be created' return ret res = __salt__['kubernetes.create_pod'](name=name, namespace=namespace, metadata=metadata, spec=spec, source=source, template=template, saltenv=__env__, **kwargs) ret['changes']['{0}.{1}'.format(namespace, name)] = { 'old': {}, 'new': res} else: if __opts__['test']: ret['result'] = None return ret # TODO: fix replace_namespaced_pod validation issues ret['comment'] = 'salt is currently unable to replace a pod without ' \ 'deleting it. Please perform the removal of the pod requiring ' \ 'the \'pod_absent\' state if this is the desired behaviour.' ret['result'] = False return ret ret['changes'] = { 'metadata': metadata, 'spec': spec } ret['result'] = True return ret def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label does not exist' return ret if __opts__['test']: ret['comment'] = 'The label is going to be deleted' ret['result'] = None return ret __salt__['kubernetes.node_remove_label']( node_name=node, label_name=name, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label': { 'new': 'absent', 'old': 'present'}} ret['comment'] = 'Label removed from node' return ret def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) folder = name.strip("/") + "/" labels_to_drop = [] new_labels = [] for label in labels: if label.startswith(folder): labels_to_drop.append(label) else: new_labels.append(label) if not labels_to_drop: ret['result'] = True if not __opts__['test'] else None ret['comment'] = 'The label folder does not exist' return ret if __opts__['test']: ret['comment'] = 'The label folder is going to be deleted' ret['result'] = None return ret for label in labels_to_drop: __salt__['kubernetes.node_remove_label']( node_name=node, label_name=label, **kwargs) ret['result'] = True ret['changes'] = { 'kubernetes.node_label_folder_absent': { 'old': list(labels), 'new': new_labels, } } ret['comment'] = 'Label folder removed from node' return ret
saltstack/salt
salt/proxy/esxvm.py
init
python
def init(opts): ''' This function gets called when the proxy starts up. For login the protocol and port are cached. ''' log.debug('Initting esxvm proxy module in process %s', os.getpid()) log.debug('Validating esxvm proxy input') proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {})) log.trace('proxy_conf = %s', proxy_conf) # TODO json schema validation # Save mandatory fields in cache for key in ('vcenter', 'datacenter', 'mechanism'): DETAILS[key] = proxy_conf[key] # Additional validation if DETAILS['mechanism'] == 'userpass': if 'username' not in proxy_conf: raise excs.InvalidProxyInputError( 'Mechanism is set to \'userpass\' , but no ' '\'username\' key found in pillar for this proxy.') if 'passwords' not in proxy_conf: raise excs.InvalidProxyInputError( 'Mechanism is set to \'userpass\' , but no ' '\'passwords\' key found in pillar for this proxy.') for key in ('username', 'passwords'): DETAILS[key] = proxy_conf[key] else: if 'domain' not in proxy_conf: raise excs.InvalidProxyInputError( 'Mechanism is set to \'sspi\' , but no ' '\'domain\' key found in pillar for this proxy.') if 'principal' not in proxy_conf: raise excs.InvalidProxyInputError( 'Mechanism is set to \'sspi\' , but no ' '\'principal\' key found in pillar for this proxy.') for key in ('domain', 'principal'): DETAILS[key] = proxy_conf[key] # Save optional DETAILS['protocol'] = proxy_conf.get('protocol') DETAILS['port'] = proxy_conf.get('port') # Test connection if DETAILS['mechanism'] == 'userpass': # Get the correct login details log.debug('Retrieving credentials and testing vCenter connection for ' 'mehchanism \'userpass\'') try: username, password = find_credentials() DETAILS['password'] = password except excs.SaltSystemExit as err: log.critical('Error: %s', err) return False return True
This function gets called when the proxy starts up. For login the protocol and port are cached.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxvm.py#L180-L234
[ "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 find_credentials():\n '''\n Cycle through all the possible credentials and return the first one that\n works.\n '''\n\n # if the username and password were already found don't go through the\n # connection process again\n if 'username' in DETAILS and 'password' in DETAILS:\n return DETAILS['username'], DETAILS['password']\n\n passwords = __pillar__['proxy']['passwords']\n for password in passwords:\n DETAILS['password'] = password\n if not __salt__['vsphere.test_vcenter_connection']():\n # We are unable to authenticate\n continue\n # If we have data returned from above, we've successfully authenticated.\n return DETAILS['username'], password\n # We've reached the end of the list without successfully authenticating.\n raise excs.VMwareConnectionError('Cannot complete login due to '\n 'incorrect credentials.')\n" ]
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing VMWare ESXi virtual machines. Dependencies ============ - pyVmomi - jsonschema Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. This can now happen from the proxy's configuration file. Example pillars: ``userpass`` mechanism: .. code-block:: yaml proxy: proxytype: esxvm datacenter: <datacenter name> vcenter: <ip or dns name of parent vcenter> mechanism: userpass username: <vCenter username> passwords: (required if userpass is used) - first_password - second_password - third_password ``sspi`` mechanism: .. code-block:: yaml proxy: proxytype: esxvm datacenter: <datacenter name> vcenter: <ip or dns name of parent vcenter> mechanism: sspi domain: <user domain> principal: <host kerberos principal> proxytype ^^^^^^^^^ To use this Proxy Module, set this to ``esxvm``. datacenter ^^^^^^^^^^ Name of the datacenter where the virtual machine should be deployed. Required. vcenter ^^^^^^^ The location of the VMware vCenter server (host of ip) where the virtual machine should be managed. Required. mechanism ^^^^^^^^^ The mechanism used to connect to the vCenter server. Supported values are ``userpass`` and ``sspi``. Required. Note: Connections are attempted using all (``username``, ``password``) combinations on proxy startup. username ^^^^^^^^ The username used to login to the host, such as ``root``. Required if mechanism is ``userpass``. passwords ^^^^^^^^^ A list of passwords to be used to try and login to the vCenter server. At least one password in this list is required if mechanism is ``userpass``. When the proxy comes up, it will try the passwords listed in order. domain ^^^^^^ User realm domain. Required if mechanism is ``sspi``. principal ^^^^^^^^ Kerberos principal. Rquired if mechanism is ``sspi``. protocol ^^^^^^^^ If the ESXi host is not using the default protocol, set this value to an alternate protocol. Default is ``https``. port ^^^^ If the ESXi host is not using the default port, set this value to an alternate port. Default is ``443``. Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the vCenter server in the pillar. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. To start a proxy minion one needs to establish its identity <id>: .. code-block:: bash salt-proxy --proxyid <proxy_id> On the machine that will run the proxy, make sure there is a configuration file present. By default this is ``/etc/salt/proxy``. If in a different location, the ``<configuration_folder>`` has to be specified when running the proxy: file with at least the following in it: .. code-block:: bash salt-proxy --proxyid <proxy_id> -c <configuration_folder> Commands -------- Once the proxy is running it will connect back to the specified master and individual commands can be runs against it: .. code-block:: bash # Master - minion communication salt <proxy_id> test.ping # Test vcenter connection salt <proxy_id> vsphere.test_vcenter_connection States ------ Associated states are documented in :mod:`salt.states.esxvm </ref/states/all/salt.states.esxvm>`. Look there to find an example structure for Pillar as well as an example ``.sls`` file for configuring an ESX virtual machine from scratch. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt Libs import salt.exceptions as excs from salt.utils.dictupdate import merge # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['esxvm'] # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'esxvm' def __virtual__(): ''' Only load if the vsphere execution module is available. ''' return __virtualname__ def ping(): ''' Returns True. CLI Example: .. code-block:: bash salt esx-vm test.ping ''' return True def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('ESX vm proxy shutdown() called...') def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works. ''' # if the username and password were already found don't go through the # connection process again if 'username' in DETAILS and 'password' in DETAILS: return DETAILS['username'], DETAILS['password'] passwords = __pillar__['proxy']['passwords'] for password in passwords: DETAILS['password'] = password if not __salt__['vsphere.test_vcenter_connection'](): # We are unable to authenticate continue # If we have data returned from above, we've successfully authenticated. return DETAILS['username'], password # We've reached the end of the list without successfully authenticating. raise excs.VMwareConnectionError('Cannot complete login due to ' 'incorrect credentials.') def get_details(): ''' Function that returns the cached details ''' return DETAILS
saltstack/salt
salt/proxy/esxvm.py
find_credentials
python
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works. ''' # if the username and password were already found don't go through the # connection process again if 'username' in DETAILS and 'password' in DETAILS: return DETAILS['username'], DETAILS['password'] passwords = __pillar__['proxy']['passwords'] for password in passwords: DETAILS['password'] = password if not __salt__['vsphere.test_vcenter_connection'](): # We are unable to authenticate continue # If we have data returned from above, we've successfully authenticated. return DETAILS['username'], password # We've reached the end of the list without successfully authenticating. raise excs.VMwareConnectionError('Cannot complete login due to ' 'incorrect credentials.')
Cycle through all the possible credentials and return the first one that works.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxvm.py#L258-L279
null
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing VMWare ESXi virtual machines. Dependencies ============ - pyVmomi - jsonschema Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. This can now happen from the proxy's configuration file. Example pillars: ``userpass`` mechanism: .. code-block:: yaml proxy: proxytype: esxvm datacenter: <datacenter name> vcenter: <ip or dns name of parent vcenter> mechanism: userpass username: <vCenter username> passwords: (required if userpass is used) - first_password - second_password - third_password ``sspi`` mechanism: .. code-block:: yaml proxy: proxytype: esxvm datacenter: <datacenter name> vcenter: <ip or dns name of parent vcenter> mechanism: sspi domain: <user domain> principal: <host kerberos principal> proxytype ^^^^^^^^^ To use this Proxy Module, set this to ``esxvm``. datacenter ^^^^^^^^^^ Name of the datacenter where the virtual machine should be deployed. Required. vcenter ^^^^^^^ The location of the VMware vCenter server (host of ip) where the virtual machine should be managed. Required. mechanism ^^^^^^^^^ The mechanism used to connect to the vCenter server. Supported values are ``userpass`` and ``sspi``. Required. Note: Connections are attempted using all (``username``, ``password``) combinations on proxy startup. username ^^^^^^^^ The username used to login to the host, such as ``root``. Required if mechanism is ``userpass``. passwords ^^^^^^^^^ A list of passwords to be used to try and login to the vCenter server. At least one password in this list is required if mechanism is ``userpass``. When the proxy comes up, it will try the passwords listed in order. domain ^^^^^^ User realm domain. Required if mechanism is ``sspi``. principal ^^^^^^^^ Kerberos principal. Rquired if mechanism is ``sspi``. protocol ^^^^^^^^ If the ESXi host is not using the default protocol, set this value to an alternate protocol. Default is ``https``. port ^^^^ If the ESXi host is not using the default port, set this value to an alternate port. Default is ``443``. Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the vCenter server in the pillar. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. To start a proxy minion one needs to establish its identity <id>: .. code-block:: bash salt-proxy --proxyid <proxy_id> On the machine that will run the proxy, make sure there is a configuration file present. By default this is ``/etc/salt/proxy``. If in a different location, the ``<configuration_folder>`` has to be specified when running the proxy: file with at least the following in it: .. code-block:: bash salt-proxy --proxyid <proxy_id> -c <configuration_folder> Commands -------- Once the proxy is running it will connect back to the specified master and individual commands can be runs against it: .. code-block:: bash # Master - minion communication salt <proxy_id> test.ping # Test vcenter connection salt <proxy_id> vsphere.test_vcenter_connection States ------ Associated states are documented in :mod:`salt.states.esxvm </ref/states/all/salt.states.esxvm>`. Look there to find an example structure for Pillar as well as an example ``.sls`` file for configuring an ESX virtual machine from scratch. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt Libs import salt.exceptions as excs from salt.utils.dictupdate import merge # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['esxvm'] # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'esxvm' def __virtual__(): ''' Only load if the vsphere execution module is available. ''' return __virtualname__ def init(opts): ''' This function gets called when the proxy starts up. For login the protocol and port are cached. ''' log.debug('Initting esxvm proxy module in process %s', os.getpid()) log.debug('Validating esxvm proxy input') proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {})) log.trace('proxy_conf = %s', proxy_conf) # TODO json schema validation # Save mandatory fields in cache for key in ('vcenter', 'datacenter', 'mechanism'): DETAILS[key] = proxy_conf[key] # Additional validation if DETAILS['mechanism'] == 'userpass': if 'username' not in proxy_conf: raise excs.InvalidProxyInputError( 'Mechanism is set to \'userpass\' , but no ' '\'username\' key found in pillar for this proxy.') if 'passwords' not in proxy_conf: raise excs.InvalidProxyInputError( 'Mechanism is set to \'userpass\' , but no ' '\'passwords\' key found in pillar for this proxy.') for key in ('username', 'passwords'): DETAILS[key] = proxy_conf[key] else: if 'domain' not in proxy_conf: raise excs.InvalidProxyInputError( 'Mechanism is set to \'sspi\' , but no ' '\'domain\' key found in pillar for this proxy.') if 'principal' not in proxy_conf: raise excs.InvalidProxyInputError( 'Mechanism is set to \'sspi\' , but no ' '\'principal\' key found in pillar for this proxy.') for key in ('domain', 'principal'): DETAILS[key] = proxy_conf[key] # Save optional DETAILS['protocol'] = proxy_conf.get('protocol') DETAILS['port'] = proxy_conf.get('port') # Test connection if DETAILS['mechanism'] == 'userpass': # Get the correct login details log.debug('Retrieving credentials and testing vCenter connection for ' 'mehchanism \'userpass\'') try: username, password = find_credentials() DETAILS['password'] = password except excs.SaltSystemExit as err: log.critical('Error: %s', err) return False return True def ping(): ''' Returns True. CLI Example: .. code-block:: bash salt esx-vm test.ping ''' return True def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('ESX vm proxy shutdown() called...') def get_details(): ''' Function that returns the cached details ''' return DETAILS
saltstack/salt
salt/modules/devmap.py
multipath_flush
python
def multipath_flush(device): ''' Device-Mapper Multipath flush CLI Example: .. code-block:: bash salt '*' devmap.multipath_flush mpath1 ''' if not os.path.exists(device): return '{0} does not exist'.format(device) cmd = 'multipath -f {0}'.format(device) return __salt__['cmd.run'](cmd).splitlines()
Device-Mapper Multipath flush CLI Example: .. code-block:: bash salt '*' devmap.multipath_flush mpath1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/devmap.py#L23-L37
null
# -*- coding: utf-8 -*- ''' Device-Mapper module ''' from __future__ import absolute_import, print_function, unicode_literals import os.path def multipath_list(): ''' Device-Mapper Multipath list CLI Example: .. code-block:: bash salt '*' devmap.multipath_list ''' cmd = 'multipath -l' return __salt__['cmd.run'](cmd).splitlines()
saltstack/salt
salt/states/debconfmod.py
set_file
python
def set_file(name, source, template=None, context=None, defaults=None, **kwargs): ''' Set debconf selections from a file or a template .. code-block:: yaml <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections?saltenv=myenvironment <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections.jinja2 - template: jinja - context: some_value: "false" source: The location of the file containing the package selections template If this setting is applied then the named templating engine will be used to render the package selections file, currently jinja, mako, and wempy are supported context Overrides default context variables passed to the template. defaults Default context passed to the template. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if context is None: context = {} elif not isinstance(context, dict): ret['result'] = False ret['comment'] = 'Context must be formed as a dict' return ret if defaults is None: defaults = {} elif not isinstance(defaults, dict): ret['result'] = False ret['comment'] = 'Defaults must be formed as a dict' return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Debconf selections would have been set.' return ret if template: result = __salt__['debconf.set_template'](source, template, context, defaults, **kwargs) else: result = __salt__['debconf.set_file'](source, **kwargs) if result: ret['comment'] = 'Debconf selections were set.' else: ret['result'] = False ret['comment'] = 'Unable to set debconf selections from file.' return ret
Set debconf selections from a file or a template .. code-block:: yaml <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections?saltenv=myenvironment <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections.jinja2 - template: jinja - context: some_value: "false" source: The location of the file containing the package selections template If this setting is applied then the named templating engine will be used to render the package selections file, currently jinja, mako, and wempy are supported context Overrides default context variables passed to the template. defaults Default context passed to the template.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/debconfmod.py#L85-L155
null
# -*- coding: utf-8 -*- ''' Management of debconf selections ================================ :depends: - debconf-utils package The debconfmod state module manages the enforcement of debconf selections, this state can set those selections prior to package installation. Available Functions ------------------- The debconfmod state has two functions, the ``set`` and ``set_file`` functions set Set debconf selections from the state itself set_file Set debconf selections from a file .. code-block:: yaml nullmailer-debconf: debconf.set: - name: nullmailer - data: 'shared/mailname': {'type': 'string', 'value': 'server.domain.tld'} 'nullmailer/relayhost': {'type': 'string', 'value': 'mail.domain.tld'} ferm-debconf: debconf.set: - name: ferm - data: 'ferm/enable': {'type': 'boolean', 'value': True} .. note:: Due to how PyYAML imports nested dicts (see :ref:`here <yaml-idiosyncrasies>`), the values in the ``data`` dict must be indented four spaces instead of two. If you're setting debconf values that requires `dpkg-reconfigure`, you can use the ``onchanges`` requisite to reconfigure your package: .. code-block:: yaml set-default-shell: debconf.set: - name: dash - data: 'dash/sh': {'type': 'boolean', 'value': false} reconfigure-dash: cmd.run: - name: dpkg-reconfigure -f noninteractive dash - onchanges: - debconf: set-default-shell Every time the ``set-default-shell`` state changes, the ``reconfigure-dash`` state will also run. .. note:: For boolean types, the value should be ``true`` or ``false``, not ``'true'`` or ``'false'``. ''' from __future__ import absolute_import, print_function, unicode_literals from salt.ext import six # Define the module's virtual name __virtualname__ = 'debconf' def __virtual__(): ''' Confirm this module is on a Debian based system ''' if __grains__['os_family'] != 'Debian': return False # Check that debconf was loaded if 'debconf.show' not in __salt__: return False return __virtualname__ def set(name, data, **kwargs): ''' Set debconf selections .. code-block:: yaml <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} name: The package name to set answers for. data: A set of questions/answers for debconf. Note that everything under this must be indented twice. question: The question the is being pre-answered type: The type of question that is being asked (string, boolean, select, etc.) value: The answer to the question ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} current = __salt__['debconf.show'](name) for (key, args) in six.iteritems(data): # For debconf data, valid booleans are 'true' and 'false'; # But str()'ing the args['value'] will result in 'True' and 'False' # which will be ignored and overridden by a dpkg-reconfigure. # So we should manually set these values to lowercase ones, # before any str() call is performed. if args['type'] == 'boolean': args['value'] = 'true' if args['value'] else 'false' if current is not None and [key, args['type'], six.text_type(args['value'])] in current: if ret['comment'] is '': ret['comment'] = 'Unchanged answers: ' ret['comment'] += ('{0} ').format(key) else: if __opts__['test']: ret['result'] = None ret['changes'][key] = ('New value: {0}').format(args['value']) else: if __salt__['debconf.set'](name, key, args['type'], args['value']): if args['type'] == 'password': ret['changes'][key] = '(password hidden)' else: ret['changes'][key] = ('{0}').format(args['value']) else: ret['result'] = False ret['comment'] = 'Some settings failed to be applied.' ret['changes'][key] = 'Failed to set!' if not ret['changes']: ret['comment'] = 'All specified answers are already set' return ret
saltstack/salt
salt/states/debconfmod.py
set
python
def set(name, data, **kwargs): ''' Set debconf selections .. code-block:: yaml <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} name: The package name to set answers for. data: A set of questions/answers for debconf. Note that everything under this must be indented twice. question: The question the is being pre-answered type: The type of question that is being asked (string, boolean, select, etc.) value: The answer to the question ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} current = __salt__['debconf.show'](name) for (key, args) in six.iteritems(data): # For debconf data, valid booleans are 'true' and 'false'; # But str()'ing the args['value'] will result in 'True' and 'False' # which will be ignored and overridden by a dpkg-reconfigure. # So we should manually set these values to lowercase ones, # before any str() call is performed. if args['type'] == 'boolean': args['value'] = 'true' if args['value'] else 'false' if current is not None and [key, args['type'], six.text_type(args['value'])] in current: if ret['comment'] is '': ret['comment'] = 'Unchanged answers: ' ret['comment'] += ('{0} ').format(key) else: if __opts__['test']: ret['result'] = None ret['changes'][key] = ('New value: {0}').format(args['value']) else: if __salt__['debconf.set'](name, key, args['type'], args['value']): if args['type'] == 'password': ret['changes'][key] = '(password hidden)' else: ret['changes'][key] = ('{0}').format(args['value']) else: ret['result'] = False ret['comment'] = 'Some settings failed to be applied.' ret['changes'][key] = 'Failed to set!' if not ret['changes']: ret['comment'] = 'All specified answers are already set' return ret
Set debconf selections .. code-block:: yaml <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} name: The package name to set answers for. data: A set of questions/answers for debconf. Note that everything under this must be indented twice. question: The question the is being pre-answered type: The type of question that is being asked (string, boolean, select, etc.) value: The answer to the question
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/debconfmod.py#L158-L234
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Management of debconf selections ================================ :depends: - debconf-utils package The debconfmod state module manages the enforcement of debconf selections, this state can set those selections prior to package installation. Available Functions ------------------- The debconfmod state has two functions, the ``set`` and ``set_file`` functions set Set debconf selections from the state itself set_file Set debconf selections from a file .. code-block:: yaml nullmailer-debconf: debconf.set: - name: nullmailer - data: 'shared/mailname': {'type': 'string', 'value': 'server.domain.tld'} 'nullmailer/relayhost': {'type': 'string', 'value': 'mail.domain.tld'} ferm-debconf: debconf.set: - name: ferm - data: 'ferm/enable': {'type': 'boolean', 'value': True} .. note:: Due to how PyYAML imports nested dicts (see :ref:`here <yaml-idiosyncrasies>`), the values in the ``data`` dict must be indented four spaces instead of two. If you're setting debconf values that requires `dpkg-reconfigure`, you can use the ``onchanges`` requisite to reconfigure your package: .. code-block:: yaml set-default-shell: debconf.set: - name: dash - data: 'dash/sh': {'type': 'boolean', 'value': false} reconfigure-dash: cmd.run: - name: dpkg-reconfigure -f noninteractive dash - onchanges: - debconf: set-default-shell Every time the ``set-default-shell`` state changes, the ``reconfigure-dash`` state will also run. .. note:: For boolean types, the value should be ``true`` or ``false``, not ``'true'`` or ``'false'``. ''' from __future__ import absolute_import, print_function, unicode_literals from salt.ext import six # Define the module's virtual name __virtualname__ = 'debconf' def __virtual__(): ''' Confirm this module is on a Debian based system ''' if __grains__['os_family'] != 'Debian': return False # Check that debconf was loaded if 'debconf.show' not in __salt__: return False return __virtualname__ def set_file(name, source, template=None, context=None, defaults=None, **kwargs): ''' Set debconf selections from a file or a template .. code-block:: yaml <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections?saltenv=myenvironment <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections.jinja2 - template: jinja - context: some_value: "false" source: The location of the file containing the package selections template If this setting is applied then the named templating engine will be used to render the package selections file, currently jinja, mako, and wempy are supported context Overrides default context variables passed to the template. defaults Default context passed to the template. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if context is None: context = {} elif not isinstance(context, dict): ret['result'] = False ret['comment'] = 'Context must be formed as a dict' return ret if defaults is None: defaults = {} elif not isinstance(defaults, dict): ret['result'] = False ret['comment'] = 'Defaults must be formed as a dict' return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Debconf selections would have been set.' return ret if template: result = __salt__['debconf.set_template'](source, template, context, defaults, **kwargs) else: result = __salt__['debconf.set_file'](source, **kwargs) if result: ret['comment'] = 'Debconf selections were set.' else: ret['result'] = False ret['comment'] = 'Unable to set debconf selections from file.' return ret
saltstack/salt
salt/engines/docker_events.py
start
python
def start(docker_url='unix://var/run/docker.sock', timeout=CLIENT_TIMEOUT, tag='salt/engines/docker_events', filters=None): ''' Scan for Docker events and fire events Example Config .. code-block:: yaml engines: - docker_events: docker_url: unix://var/run/docker.sock filters: event: - start - stop - die - oom The config above sets up engines to listen for events from the Docker daemon and publish them to the Salt event bus. For filter reference, see https://docs.docker.com/engine/reference/commandline/events/ ''' if __opts__.get('__role') == 'master': fire_master = salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event else: fire_master = None def fire(tag, msg): ''' How to fire the event ''' if fire_master: fire_master(msg, tag) else: __salt__['event.send'](tag, msg) try: # docker-py 2.0 renamed this client attribute client = docker.APIClient(base_url=docker_url, timeout=timeout) except AttributeError: client = docker.Client(base_url=docker_url, timeout=timeout) try: events = client.events(filters=filters) for event in events: data = salt.utils.json.loads(event.decode(__salt_system_encoding__, errors='replace')) # https://github.com/docker/cli/blob/master/cli/command/system/events.go#L109 # https://github.com/docker/engine-api/blob/master/types/events/events.go # Each output includes the event type, actor id, name and action. # status field can be ommited if data['Action']: fire('{0}/{1}'.format(tag, data['Action']), data) else: fire('{0}/{1}'.format(tag, data['status']), data) except Exception: traceback.print_exc()
Scan for Docker events and fire events Example Config .. code-block:: yaml engines: - docker_events: docker_url: unix://var/run/docker.sock filters: event: - start - stop - die - oom The config above sets up engines to listen for events from the Docker daemon and publish them to the Salt event bus. For filter reference, see https://docs.docker.com/engine/reference/commandline/events/
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/docker_events.py#L42-L105
[ "def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False):\n '''\n Return an event object suitable for the named transport\n '''\n # TODO: AIO core is separate from transport\n if opts['transport'] in ('zeromq', 'tcp', 'detect'):\n return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)\n", "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 fire(tag, msg):\n '''\n How to fire the event\n '''\n if fire_master:\n fire_master(msg, tag)\n else:\n __salt__['event.send'](tag, msg)\n" ]
# -*- coding: utf-8 -*- ''' Send events from Docker events :Depends: Docker API >= 1.22 ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import traceback import salt.utils.json import salt.utils.event # pylint: disable=import-error try: import docker import docker.utils HAS_DOCKER_PY = True except ImportError: HAS_DOCKER_PY = False log = logging.getLogger(__name__) # pylint: disable=invalid-name # Default timeout as of docker-py 1.0.0 CLIENT_TIMEOUT = 60 # Define the module's virtual name __virtualname__ = 'docker_events' def __virtual__(): ''' Only load if docker libs are present ''' if not HAS_DOCKER_PY: return (False, 'Docker_events engine could not be imported') return True
saltstack/salt
salt/modules/infoblox.py
_get_config
python
def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config
Return configuration user passed api_opts override salt config.get vars
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L58-L75
null
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
update_host
python
def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts)
Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L120-L133
[ "def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts):\n '''\n Get host information\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call infoblox.get_host hostname.domain.ca\n salt-call infoblox.get_host ipv4addr=123.123.122.12\n salt-call infoblox.get_host mac=00:50:56:84:6e:ae\n '''\n infoblox = _get_infoblox(**api_opts)\n host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields)\n return host\n", "def update_object(objref, data, **api_opts):\n '''\n Update raw infoblox object. This is a low level api call.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call infoblox.update_object objref=[ref_of_object] data={}\n '''\n if '__opts__' in globals() and __opts__['test']:\n return {'Test': 'Would attempt to update object: {0}'.format(objref)}\n infoblox = _get_infoblox(**api_opts)\n return infoblox.update_object(objref, data)\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
update_object
python
def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data)
Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L136-L149
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
delete_object
python
def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref)
Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L152-L165
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
create_object
python
def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data)
Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L168-L181
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_object
python
def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result)
Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L184-L199
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
create_cname
python
def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host
Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ }
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L202-L220
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_cname
python
def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o
Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L223-L236
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
update_cname
python
def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts)
Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L239-L258
[ "def update_object(objref, data, **api_opts):\n '''\n Update raw infoblox object. This is a low level api call.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call infoblox.update_object objref=[ref_of_object] data={}\n '''\n if '__opts__' in globals() and __opts__['test']:\n return {'Test': 'Would attempt to update object: {0}'.format(objref)}\n infoblox = _get_infoblox(**api_opts)\n return infoblox.update_object(objref, data)\n", "def get_cname(name=None, canonical=None, return_fields=None, **api_opts):\n '''\n Get CNAME information.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call infoblox.get_cname name=example.example.com\n salt-call infoblox.get_cname canonical=example-ha-0.example.com\n '''\n infoblox = _get_infoblox(**api_opts)\n o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields)\n return o\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
delete_cname
python
def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True
Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L261-L277
[ "def delete_object(objref, **api_opts):\n '''\n Delete infoblox object. This is a low level api call.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call infoblox.delete_object objref=[ref_of_object]\n '''\n if '__opts__' in globals() and __opts__['test']:\n return {'Test': 'Would attempt to delete object: {0}'.format(objref)}\n infoblox = _get_infoblox(**api_opts)\n return infoblox.delete_object(objref)\n", "def get_cname(name=None, canonical=None, return_fields=None, **api_opts):\n '''\n Get CNAME information.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call infoblox.get_cname name=example.example.com\n salt-call infoblox.get_cname canonical=example-ha-0.example.com\n '''\n infoblox = _get_infoblox(**api_opts)\n o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields)\n return o\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_host
python
def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host
Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L280-L294
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_host_advanced
python
def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host
Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L297-L309
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_host_domainname
python
def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None
Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L312-L348
[ "def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts):\n '''\n Get host information\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call infoblox.get_host hostname.domain.ca\n salt-call infoblox.get_host ipv4addr=123.123.122.12\n salt-call infoblox.get_host mac=00:50:56:84:6e:ae\n '''\n infoblox = _get_infoblox(**api_opts)\n host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields)\n return host\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_host_hostname
python
def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name
Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L351-L382
[ "def get_host_domainname(name, domains=None, **api_opts):\n '''\n Get host domain name\n\n If no domains are passed, the hostname is checked for a zone in infoblox,\n if no zone split on first dot.\n\n If domains are provided, the best match out of the list is returned.\n\n If none are found the return is None\n\n dots at end of names are ignored.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call uwl.get_host_domainname name=localhost.t.domain.com \\\n domains=['domain.com', 't.domain.com.']\n\n # returns: t.domain.com\n '''\n name = name.lower().rstrip('.')\n if not domains:\n data = get_host(name=name, **api_opts)\n if data and 'zone' in data:\n return data['zone'].lower()\n else:\n if name.count('.') > 1:\n return name[name.find('.')+1:]\n return name\n match = ''\n for d in domains:\n d = d.lower().rstrip('.')\n if name.endswith(d) and len(d) > len(match):\n match = d\n return match if match else None\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_host_mac
python
def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None
Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L385-L407
[ "def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts):\n '''\n Get host information\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call infoblox.get_host hostname.domain.ca\n salt-call infoblox.get_host ipv4addr=123.123.122.12\n salt-call infoblox.get_host mac=00:50:56:84:6e:ae\n '''\n infoblox = _get_infoblox(**api_opts)\n host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields)\n return host\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_host_ipv4
python
def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None
Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L410-L433
[ "def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts):\n '''\n Get host information\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call infoblox.get_host hostname.domain.ca\n salt-call infoblox.get_host ipv4addr=123.123.122.12\n salt-call infoblox.get_host mac=00:50:56:84:6e:ae\n '''\n infoblox = _get_infoblox(**api_opts)\n host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields)\n return host\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_host_ipv4addr_info
python
def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields)
Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L436-L451
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_host_ipv6addr_info
python
def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields)
Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L454-L467
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_network
python
def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields)
Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L470-L487
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
delete_host
python
def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr)
Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L490-L505
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_ipv4_range
python
def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields)
Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L541-L552
[ "def _get_infoblox(**api_opts):\n config = _get_config(**api_opts)\n # TODO: perhaps cache in __opts__\n cache_key = 'infoblox_session_{0},{1},{2}'.format(\n config['api_url'], config['api_user'], config['api_key'])\n if cache_key in cache:\n timedelta = int(time.time()) - cache[cache_key]['time']\n if cache[cache_key]['obj'] and timedelta < 60:\n return cache[cache_key]['obj']\n c = {}\n c['time'] = int(time.time())\n c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'],\n api_user=config['api_user'], api_key=config['api_key'])\n cache[cache_key] = c\n return c['obj']\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
delete_ipv4_range
python
def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True
Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L555-L569
[ "def delete_object(objref, **api_opts):\n '''\n Delete infoblox object. This is a low level api call.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call infoblox.delete_object objref=[ref_of_object]\n '''\n if '__opts__' in globals() and __opts__['test']:\n return {'Test': 'Would attempt to delete object: {0}'.format(objref)}\n infoblox = _get_infoblox(**api_opts)\n return infoblox.delete_object(objref)\n", "def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts):\n '''\n Get ip range\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call infoblox.get_ipv4_range start_addr=123.123.122.12\n '''\n infoblox = _get_infoblox(**api_opts)\n return infoblox.get_range(start_addr, end_addr, return_fields)\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
get_a
python
def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r
Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L610-L629
[ "def get_object(objref, data=None, return_fields=None, max_results=None,\n ensure_none_or_one_result=False, **api_opts):\n '''\n Get raw infoblox object. This is a low level api call.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call infoblox.get_object objref=[_ref of object]\n '''\n if not data:\n data = {}\n infoblox = _get_infoblox(**api_opts)\n return infoblox.get_object(objref, data, return_fields,\n max_results, ensure_none_or_one_result)\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
saltstack/salt
salt/modules/infoblox.py
delete_a
python
def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True ''' r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] for ri in r: ret.append(delete_object(ri['_ref'], **api_opts)) return ret
Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call infoblox.delete_a name=acname.example.com allow_array=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L632-L655
[ "def delete_object(objref, **api_opts):\n '''\n Delete infoblox object. This is a low level api call.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call infoblox.delete_object objref=[ref_of_object]\n '''\n if '__opts__' in globals() and __opts__['test']:\n return {'Test': 'Would attempt to delete object: {0}'.format(objref)}\n infoblox = _get_infoblox(**api_opts)\n return infoblox.delete_object(objref)\n", "def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts):\n '''\n Get A record\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-call infoblox.get_a name=abc.example.com\n salt-call infoblox.get_a ipv4addr=192.168.3.5\n '''\n data = {}\n if name:\n data['name'] = name\n if ipv4addr:\n data['ipv4addr'] = ipv4addr\n r = get_object('record:a', data=data, **api_opts)\n if r and len(r) > 1 and not allow_array:\n raise Exception('More than one result, use allow_array to return the data')\n return r\n" ]
# -*- coding: utf-8 -*- ''' This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. :depends: libinfoblox, https://github.com/steverweber/libinfoblox libinfoblox can be installed using `pip install libinfoblox` API documents can be found on your infoblox server at: https://INFOBLOX/wapidoc :configuration: The following configuration defaults can be defined (pillar or config files '/etc/salt/master.d/infoblox.conf'): .. code-block:: python infoblox.config: api_sslverify: True api_url: 'https://INFOBLOX/wapi/v1.2.1' api_user: 'username' api_key: 'password' Many of the functions accept `api_opts` to override the API config. .. code-block:: bash salt-call infoblox.get_host name=my.host.com \ api_url: 'https://INFOBLOX/wapi/v1.2.1' \ api_user=admin \ api_key=passs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time # Import Salt libs from salt.ext import six IMPORT_ERR = None try: import libinfoblox except Exception as exc: IMPORT_ERR = six.text_type(exc) __virtualname__ = 'infoblox' def __virtual__(): return (IMPORT_ERR is None, IMPORT_ERR) cache = {} def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): config_key = '{0}.config'.format(__virtualname__) config.update(__salt__['config.get'](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): config[k] = api_opts[k] return config def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ cache_key = 'infoblox_session_{0},{1},{2}'.format( config['api_url'], config['api_user'], config['api_key']) if cache_key in cache: timedelta = int(time.time()) - cache[cache_key]['time'] if cache[cache_key]['obj'] and timedelta < 60: return cache[cache_key]['obj'] c = {} c['time'] = int(time.time()) c['obj'] = libinfoblox.Session(api_sslverify=config['api_sslverify'], api_url=config['api_url'], api_user=config['api_user'], api_key=config['api_key']) cache[cache_key] = c return c['obj'] def diff_objects(obja, objb): ''' Diff two complex infoblox objects. This is used from salt states to detect changes in objects. Using ``func:nextavailableip`` will not cause a diff if the ipaddress is in range ''' return libinfoblox.diff_obj(obja, objb) def is_ipaddr_in_ipfunc_range(ipaddr, ipfunc): ''' Return true if the ipaddress is in the range of the nextavailableip function CLI Example: .. code-block:: bash salt-call infoblox.is_ipaddr_in_ipfunc_range \ ipaddr="10.0.2.2" ipfunc="func:nextavailableip:10.0.0.0/8" ''' return libinfoblox.is_ipaddr_in_ipfunc_range(ipaddr, ipfunc) def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=name, **api_opts) return update_object(objref=o['_ref'], data=data, **api_opts) def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to create object: {0}'.format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' if not data: data = {} infoblox = _get_infoblox(**api_opts) return infoblox.get_object(objref, data, return_fields, max_results, ensure_none_or_one_result) def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "Internal", \ "canonical": "example-ha-0.example.com" \ } ''' infoblox = _get_infoblox(**api_opts) host = infoblox.create_cname(data=data) return host def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_infoblox(**api_opts) o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields) return o def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'canonical':'example-ha-0.example.com', 'use_ttl':true, 'ttl':200, 'comment':'Salt managed CNAME'}" ''' o = get_cname(name=name, **api_opts) if not o: raise Exception('CNAME record not found') return update_object(objref=o['_ref'], data=data, **api_opts) def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com ''' cname = get_cname(name=name, canonical=canonical, **api_opts) if cname: return delete_object(cname['_ref'], **api_opts) return True def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:50:56:84:6e:ae ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields) return host def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr) return host def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None dots at end of names are ignored. CLI Example: .. code-block:: bash salt-call uwl.get_host_domainname name=localhost.t.domain.com \ domains=['domain.com', 't.domain.com.'] # returns: t.domain.com ''' name = name.lower().rstrip('.') if not domains: data = get_host(name=name, **api_opts) if data and 'zone' in data: return data['zone'].lower() else: if name.count('.') > 1: return name[name.find('.')+1:] return name match = '' for d in domains: d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d return match if match else None def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no matching domains are found the fqdn is returned. dots at end of names are ignored. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \ domains="['domain.com', 't.domain.com']" #returns: localhost.xxx salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com #returns: localhost ''' name = name.lower().rstrip('.') if not domains: return name.split('.')[0] domain = get_host_domainname(name, domains, **api_opts) if domain and domain in name: return name.rsplit('.' + domain)[0] return name def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'mac' in a: l.append(a['mac']) if allow_array: return l if l: return l[0] return None def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,enable_ddns CLI Example: .. code-block:: bash salt-call infoblox.get_network ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to delete host'} infoblox = _get_infoblox(**api_opts) return infoblox.delete_host(name, mac, ipv4addr) def create_host(data, **api_opts): ''' Add host record Avoid race conditions, use func:nextavailableip for ipv[4,6]addrs: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,external - func:nextavailableip:10.0.0.3-10.0.0.10 See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_host \ data = {'name': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'example@example.ca'}}, {'Pol8 Classification': {'value': 'Restricted'}}, {'Primary OU': {'value': 'CS'}}, {'Technical Contact': {'value': 'example@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' return create_object('record:host', data, **api_opts) def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_addr, return_fields) def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_ref'], **api_opts) else: return True def create_ipv4_range(data, **api_opts): ''' Create a ipv4 range This is a helper function to `create_object` See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_ipv4_range data={ start_addr: '129.97.150.160', end_addr: '129.97.150.170'} ''' return create_object('range', data, **api_opts) def create_a(data, **api_opts): ''' Create A record. This is a helper function to `create_object`. See your infoblox API for full `data` format. CLI Example: .. code-block:: bash salt-call infoblox.create_a \ data = name: 'fastlinux.math.example.ca' ipv4addr: '127.0.0.1' view: External ''' return create_object('record:a', data, **api_opts) def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4addr: data['ipv4addr'] = ipv4addr r = get_object('record:a', data=data, **api_opts) if r and len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to return the data') return r
saltstack/salt
salt/states/infoblox_a.py
present
python
def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): ''' Ensure infoblox A record. When you wish to update a hostname ensure `name` is set to the hostname of the current record. You can give a new name in the `data.name`. State example: .. code-block:: yaml infoblox_a.present: - name: example-ha-0.domain.com - data: name: example-ha-0.domain.com ipv4addr: 123.0.31.2 view: Internal ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} if not data: data = {} if 'name' not in data: data.update({'name': name}) if 'ipv4addr' not in data: data.update({'ipv4addr': ipv4addr}) obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts) if obj is None: # perhaps the user updated the name obj = __salt__['infoblox.get_a'](name=data['name'], ipv4addr=data['ipv4addr'], allow_array=False, **api_opts) if obj: # warn user that the data was updated and does not match ret['result'] = False ret['comment'] = '** please update the name: {0} to equal the updated data name {1}'.format(name, data['name']) return ret if obj: obj = obj[0] if not ensure_data: ret['result'] = True ret['comment'] = 'infoblox record already created (supplied fields not ensured to match)' return ret diff = __salt__['infoblox.diff_objects'](data, obj) if not diff: ret['result'] = True ret['comment'] = 'supplied fields already updated (note: removing fields might not update)' return ret if diff: ret['changes'] = {'diff': diff} if __opts__['test']: ret['result'] = None ret['comment'] = 'would attempt to update infoblox record' return ret ## TODO: perhaps need to review the output of new_obj new_obj = __salt__['infoblox.update_object'](obj['_ref'], data=data, **api_opts) ret['result'] = True ret['comment'] = 'infoblox record fields updated (note: removing fields might not update)' return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'would attempt to create infoblox record {0}'.format(data['name']) return ret new_obj_ref = __salt__['infoblox.create_a'](data=data, **api_opts) new_obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts) ret['result'] = True ret['comment'] = 'infoblox record created' ret['changes'] = {'old': 'None', 'new': {'_ref': new_obj_ref, 'data': new_obj}} return ret
Ensure infoblox A record. When you wish to update a hostname ensure `name` is set to the hostname of the current record. You can give a new name in the `data.name`. State example: .. code-block:: yaml infoblox_a.present: - name: example-ha-0.domain.com - data: name: example-ha-0.domain.com ipv4addr: 123.0.31.2 view: Internal
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/infoblox_a.py#L17-L90
null
# -*- coding: utf-8 -*- ''' Infoblox A record managment. functions accept api_opts: api_verifyssl: verify SSL [default to True or pillar value] api_url: server to connect to [default to pillar value] api_username: [default to pillar value] api_password: [default to pillar value] ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def absent(name=None, ipv4addr=None, **api_opts): ''' Ensure infoblox A record is removed. State example: .. code-block:: yaml infoblox_a.absent: - name: example-ha-0.domain.com infoblox_a.absent: - name: - ipv4addr: 127.0.23.23 ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts) if not obj: ret['result'] = True ret['comment'] = 'infoblox already removed' return ret if __opts__['test']: ret['result'] = None ret['changes'] = {'old': obj, 'new': 'absent'} return ret if __salt__['infoblox.delete_a'](name=name, ipv4addr=ipv4addr, **api_opts): ret['result'] = True ret['changes'] = {'old': obj, 'new': 'absent'} return ret
saltstack/salt
salt/states/infoblox_a.py
absent
python
def absent(name=None, ipv4addr=None, **api_opts): ''' Ensure infoblox A record is removed. State example: .. code-block:: yaml infoblox_a.absent: - name: example-ha-0.domain.com infoblox_a.absent: - name: - ipv4addr: 127.0.23.23 ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts) if not obj: ret['result'] = True ret['comment'] = 'infoblox already removed' return ret if __opts__['test']: ret['result'] = None ret['changes'] = {'old': obj, 'new': 'absent'} return ret if __salt__['infoblox.delete_a'](name=name, ipv4addr=ipv4addr, **api_opts): ret['result'] = True ret['changes'] = {'old': obj, 'new': 'absent'} return ret
Ensure infoblox A record is removed. State example: .. code-block:: yaml infoblox_a.absent: - name: example-ha-0.domain.com infoblox_a.absent: - name: - ipv4addr: 127.0.23.23
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/infoblox_a.py#L93-L124
null
# -*- coding: utf-8 -*- ''' Infoblox A record managment. functions accept api_opts: api_verifyssl: verify SSL [default to True or pillar value] api_url: server to connect to [default to pillar value] api_username: [default to pillar value] api_password: [default to pillar value] ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): ''' Ensure infoblox A record. When you wish to update a hostname ensure `name` is set to the hostname of the current record. You can give a new name in the `data.name`. State example: .. code-block:: yaml infoblox_a.present: - name: example-ha-0.domain.com - data: name: example-ha-0.domain.com ipv4addr: 123.0.31.2 view: Internal ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} if not data: data = {} if 'name' not in data: data.update({'name': name}) if 'ipv4addr' not in data: data.update({'ipv4addr': ipv4addr}) obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts) if obj is None: # perhaps the user updated the name obj = __salt__['infoblox.get_a'](name=data['name'], ipv4addr=data['ipv4addr'], allow_array=False, **api_opts) if obj: # warn user that the data was updated and does not match ret['result'] = False ret['comment'] = '** please update the name: {0} to equal the updated data name {1}'.format(name, data['name']) return ret if obj: obj = obj[0] if not ensure_data: ret['result'] = True ret['comment'] = 'infoblox record already created (supplied fields not ensured to match)' return ret diff = __salt__['infoblox.diff_objects'](data, obj) if not diff: ret['result'] = True ret['comment'] = 'supplied fields already updated (note: removing fields might not update)' return ret if diff: ret['changes'] = {'diff': diff} if __opts__['test']: ret['result'] = None ret['comment'] = 'would attempt to update infoblox record' return ret ## TODO: perhaps need to review the output of new_obj new_obj = __salt__['infoblox.update_object'](obj['_ref'], data=data, **api_opts) ret['result'] = True ret['comment'] = 'infoblox record fields updated (note: removing fields might not update)' return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'would attempt to create infoblox record {0}'.format(data['name']) return ret new_obj_ref = __salt__['infoblox.create_a'](data=data, **api_opts) new_obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts) ret['result'] = True ret['comment'] = 'infoblox record created' ret['changes'] = {'old': 'None', 'new': {'_ref': new_obj_ref, 'data': new_obj}} return ret
saltstack/salt
salt/modules/kapacitor.py
_get_url
python
def _get_url(): ''' Get the kapacitor URL. ''' protocol = __salt__['config.option']('kapacitor.protocol', 'http') host = __salt__['config.option']('kapacitor.host', 'localhost') port = __salt__['config.option']('kapacitor.port', 9092) return '{0}://{1}:{2}'.format(protocol, host, port)
Get the kapacitor URL.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L55-L63
null
# -*- coding: utf-8 -*- ''' Kapacitor execution module. :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: kapacitor.host: 'localhost' kapacitor.port: 9092 .. versionadded:: 2016.11.0 Also protocol and SSL settings could be configured:: kapacitor.unsafe_ssl: 'false' kapacitor.protocol: 'http' .. versionadded:: 2019.2.0 This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt lobs from salt.ext import six import salt.utils.http import salt.utils.json import salt.utils.path from salt.utils.decorators import memoize import logging as logger # Setup the logger log = logger.getLogger(__name__) def __virtual__(): return 'kapacitor' if salt.utils.path.which('kapacitor') else False @memoize def version(): ''' Get the kapacitor version. ''' version = __salt__['pkg.version']('kapacitor') if not version: version = six.string_types(__salt__['config.option']('kapacitor.version', 'latest')) return version def get_task(name): ''' Get a dict of data on a task. name Name of the task to get information about. CLI Example: .. code-block:: bash salt '*' kapacitor.get_task cpu ''' url = _get_url() if version() < '0.13': task_url = '{0}/task?name={1}'.format(url, name) else: task_url = '{0}/kapacitor/v1/tasks/{1}?skip-format=true'.format(url, name) response = salt.utils.http.query(task_url, status=True) if response['status'] == 404: return None data = salt.utils.json.loads(response['body']) if version() < '0.13': return { 'script': data['TICKscript'], 'type': data['Type'], 'dbrps': data['DBRPs'], 'enabled': data['Enabled'], } return { 'script': data['script'], 'type': data['type'], 'dbrps': data['dbrps'], 'enabled': data['status'] == 'enabled', } def _run_cmd(cmd): ''' Run a Kapacitor task and return a dictionary of info. ''' ret = {} env_vars = { 'KAPACITOR_URL': _get_url(), 'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'), } result = __salt__['cmd.run_all'](cmd, env=env_vars) if result.get('stdout'): ret['stdout'] = result['stdout'] if result.get('stderr'): ret['stderr'] = result['stderr'] ret['success'] = result['retcode'] == 0 return ret def define_task(name, tick_script, task_type='stream', database=None, retention_policy='default', dbrps=None): ''' Define a task. Serves as both create/update. name Name of the task. tick_script Path to the TICK script for the task. Can be a salt:// source. task_type Task type. Defaults to 'stream' dbrps A list of databases and retention policies in "dbname"."rpname" format to fetch data from. For backward compatibility, the value of 'database' and 'retention_policy' will be merged as part of dbrps. .. versionadded:: 2019.2.0 database Which database to fetch data from. retention_policy Which retention policy to fetch data from. Defaults to 'default'. CLI Example: .. code-block:: bash salt '*' kapacitor.define_task cpu salt://kapacitor/cpu.tick database=telegraf ''' if not database and not dbrps: log.error("Providing database name or dbrps is mandatory.") return False if version() < '0.13': cmd = 'kapacitor define -name {0}'.format(name) else: cmd = 'kapacitor define {0}'.format(name) if tick_script.startswith('salt://'): tick_script = __salt__['cp.cache_file'](tick_script, __env__) cmd += ' -tick {0}'.format(tick_script) if task_type: cmd += ' -type {0}'.format(task_type) if not dbrps: dbrps = [] if database and retention_policy: dbrp = '{0}.{1}'.format(database, retention_policy) dbrps.append(dbrp) if dbrps: for dbrp in dbrps: cmd += ' -dbrp {0}'.format(dbrp) return _run_cmd(cmd) def delete_task(name): ''' Delete a kapacitor task. name Name of the task to delete. CLI Example: .. code-block:: bash salt '*' kapacitor.delete_task cpu ''' return _run_cmd('kapacitor delete tasks {0}'.format(name)) def enable_task(name): ''' Enable a kapacitor task. name Name of the task to enable. CLI Example: .. code-block:: bash salt '*' kapacitor.enable_task cpu ''' return _run_cmd('kapacitor enable {0}'.format(name)) def disable_task(name): ''' Disable a kapacitor task. name Name of the task to disable. CLI Example: .. code-block:: bash salt '*' kapacitor.disable_task cpu ''' return _run_cmd('kapacitor disable {0}'.format(name))
saltstack/salt
salt/modules/kapacitor.py
get_task
python
def get_task(name): ''' Get a dict of data on a task. name Name of the task to get information about. CLI Example: .. code-block:: bash salt '*' kapacitor.get_task cpu ''' url = _get_url() if version() < '0.13': task_url = '{0}/task?name={1}'.format(url, name) else: task_url = '{0}/kapacitor/v1/tasks/{1}?skip-format=true'.format(url, name) response = salt.utils.http.query(task_url, status=True) if response['status'] == 404: return None data = salt.utils.json.loads(response['body']) if version() < '0.13': return { 'script': data['TICKscript'], 'type': data['Type'], 'dbrps': data['DBRPs'], 'enabled': data['Enabled'], } return { 'script': data['script'], 'type': data['type'], 'dbrps': data['dbrps'], 'enabled': data['status'] == 'enabled', }
Get a dict of data on a task. name Name of the task to get information about. CLI Example: .. code-block:: bash salt '*' kapacitor.get_task cpu
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L66-L106
[ "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 _get_url():\n '''\n Get the kapacitor URL.\n '''\n protocol = __salt__['config.option']('kapacitor.protocol', 'http')\n host = __salt__['config.option']('kapacitor.host', 'localhost')\n port = __salt__['config.option']('kapacitor.port', 9092)\n\n return '{0}://{1}:{2}'.format(protocol, host, port)\n" ]
# -*- coding: utf-8 -*- ''' Kapacitor execution module. :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: kapacitor.host: 'localhost' kapacitor.port: 9092 .. versionadded:: 2016.11.0 Also protocol and SSL settings could be configured:: kapacitor.unsafe_ssl: 'false' kapacitor.protocol: 'http' .. versionadded:: 2019.2.0 This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt lobs from salt.ext import six import salt.utils.http import salt.utils.json import salt.utils.path from salt.utils.decorators import memoize import logging as logger # Setup the logger log = logger.getLogger(__name__) def __virtual__(): return 'kapacitor' if salt.utils.path.which('kapacitor') else False @memoize def version(): ''' Get the kapacitor version. ''' version = __salt__['pkg.version']('kapacitor') if not version: version = six.string_types(__salt__['config.option']('kapacitor.version', 'latest')) return version def _get_url(): ''' Get the kapacitor URL. ''' protocol = __salt__['config.option']('kapacitor.protocol', 'http') host = __salt__['config.option']('kapacitor.host', 'localhost') port = __salt__['config.option']('kapacitor.port', 9092) return '{0}://{1}:{2}'.format(protocol, host, port) def _run_cmd(cmd): ''' Run a Kapacitor task and return a dictionary of info. ''' ret = {} env_vars = { 'KAPACITOR_URL': _get_url(), 'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'), } result = __salt__['cmd.run_all'](cmd, env=env_vars) if result.get('stdout'): ret['stdout'] = result['stdout'] if result.get('stderr'): ret['stderr'] = result['stderr'] ret['success'] = result['retcode'] == 0 return ret def define_task(name, tick_script, task_type='stream', database=None, retention_policy='default', dbrps=None): ''' Define a task. Serves as both create/update. name Name of the task. tick_script Path to the TICK script for the task. Can be a salt:// source. task_type Task type. Defaults to 'stream' dbrps A list of databases and retention policies in "dbname"."rpname" format to fetch data from. For backward compatibility, the value of 'database' and 'retention_policy' will be merged as part of dbrps. .. versionadded:: 2019.2.0 database Which database to fetch data from. retention_policy Which retention policy to fetch data from. Defaults to 'default'. CLI Example: .. code-block:: bash salt '*' kapacitor.define_task cpu salt://kapacitor/cpu.tick database=telegraf ''' if not database and not dbrps: log.error("Providing database name or dbrps is mandatory.") return False if version() < '0.13': cmd = 'kapacitor define -name {0}'.format(name) else: cmd = 'kapacitor define {0}'.format(name) if tick_script.startswith('salt://'): tick_script = __salt__['cp.cache_file'](tick_script, __env__) cmd += ' -tick {0}'.format(tick_script) if task_type: cmd += ' -type {0}'.format(task_type) if not dbrps: dbrps = [] if database and retention_policy: dbrp = '{0}.{1}'.format(database, retention_policy) dbrps.append(dbrp) if dbrps: for dbrp in dbrps: cmd += ' -dbrp {0}'.format(dbrp) return _run_cmd(cmd) def delete_task(name): ''' Delete a kapacitor task. name Name of the task to delete. CLI Example: .. code-block:: bash salt '*' kapacitor.delete_task cpu ''' return _run_cmd('kapacitor delete tasks {0}'.format(name)) def enable_task(name): ''' Enable a kapacitor task. name Name of the task to enable. CLI Example: .. code-block:: bash salt '*' kapacitor.enable_task cpu ''' return _run_cmd('kapacitor enable {0}'.format(name)) def disable_task(name): ''' Disable a kapacitor task. name Name of the task to disable. CLI Example: .. code-block:: bash salt '*' kapacitor.disable_task cpu ''' return _run_cmd('kapacitor disable {0}'.format(name))
saltstack/salt
salt/modules/kapacitor.py
_run_cmd
python
def _run_cmd(cmd): ''' Run a Kapacitor task and return a dictionary of info. ''' ret = {} env_vars = { 'KAPACITOR_URL': _get_url(), 'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'), } result = __salt__['cmd.run_all'](cmd, env=env_vars) if result.get('stdout'): ret['stdout'] = result['stdout'] if result.get('stderr'): ret['stderr'] = result['stderr'] ret['success'] = result['retcode'] == 0 return ret
Run a Kapacitor task and return a dictionary of info.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L109-L126
[ "def _get_url():\n '''\n Get the kapacitor URL.\n '''\n protocol = __salt__['config.option']('kapacitor.protocol', 'http')\n host = __salt__['config.option']('kapacitor.host', 'localhost')\n port = __salt__['config.option']('kapacitor.port', 9092)\n\n return '{0}://{1}:{2}'.format(protocol, host, port)\n" ]
# -*- coding: utf-8 -*- ''' Kapacitor execution module. :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: kapacitor.host: 'localhost' kapacitor.port: 9092 .. versionadded:: 2016.11.0 Also protocol and SSL settings could be configured:: kapacitor.unsafe_ssl: 'false' kapacitor.protocol: 'http' .. versionadded:: 2019.2.0 This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt lobs from salt.ext import six import salt.utils.http import salt.utils.json import salt.utils.path from salt.utils.decorators import memoize import logging as logger # Setup the logger log = logger.getLogger(__name__) def __virtual__(): return 'kapacitor' if salt.utils.path.which('kapacitor') else False @memoize def version(): ''' Get the kapacitor version. ''' version = __salt__['pkg.version']('kapacitor') if not version: version = six.string_types(__salt__['config.option']('kapacitor.version', 'latest')) return version def _get_url(): ''' Get the kapacitor URL. ''' protocol = __salt__['config.option']('kapacitor.protocol', 'http') host = __salt__['config.option']('kapacitor.host', 'localhost') port = __salt__['config.option']('kapacitor.port', 9092) return '{0}://{1}:{2}'.format(protocol, host, port) def get_task(name): ''' Get a dict of data on a task. name Name of the task to get information about. CLI Example: .. code-block:: bash salt '*' kapacitor.get_task cpu ''' url = _get_url() if version() < '0.13': task_url = '{0}/task?name={1}'.format(url, name) else: task_url = '{0}/kapacitor/v1/tasks/{1}?skip-format=true'.format(url, name) response = salt.utils.http.query(task_url, status=True) if response['status'] == 404: return None data = salt.utils.json.loads(response['body']) if version() < '0.13': return { 'script': data['TICKscript'], 'type': data['Type'], 'dbrps': data['DBRPs'], 'enabled': data['Enabled'], } return { 'script': data['script'], 'type': data['type'], 'dbrps': data['dbrps'], 'enabled': data['status'] == 'enabled', } def define_task(name, tick_script, task_type='stream', database=None, retention_policy='default', dbrps=None): ''' Define a task. Serves as both create/update. name Name of the task. tick_script Path to the TICK script for the task. Can be a salt:// source. task_type Task type. Defaults to 'stream' dbrps A list of databases and retention policies in "dbname"."rpname" format to fetch data from. For backward compatibility, the value of 'database' and 'retention_policy' will be merged as part of dbrps. .. versionadded:: 2019.2.0 database Which database to fetch data from. retention_policy Which retention policy to fetch data from. Defaults to 'default'. CLI Example: .. code-block:: bash salt '*' kapacitor.define_task cpu salt://kapacitor/cpu.tick database=telegraf ''' if not database and not dbrps: log.error("Providing database name or dbrps is mandatory.") return False if version() < '0.13': cmd = 'kapacitor define -name {0}'.format(name) else: cmd = 'kapacitor define {0}'.format(name) if tick_script.startswith('salt://'): tick_script = __salt__['cp.cache_file'](tick_script, __env__) cmd += ' -tick {0}'.format(tick_script) if task_type: cmd += ' -type {0}'.format(task_type) if not dbrps: dbrps = [] if database and retention_policy: dbrp = '{0}.{1}'.format(database, retention_policy) dbrps.append(dbrp) if dbrps: for dbrp in dbrps: cmd += ' -dbrp {0}'.format(dbrp) return _run_cmd(cmd) def delete_task(name): ''' Delete a kapacitor task. name Name of the task to delete. CLI Example: .. code-block:: bash salt '*' kapacitor.delete_task cpu ''' return _run_cmd('kapacitor delete tasks {0}'.format(name)) def enable_task(name): ''' Enable a kapacitor task. name Name of the task to enable. CLI Example: .. code-block:: bash salt '*' kapacitor.enable_task cpu ''' return _run_cmd('kapacitor enable {0}'.format(name)) def disable_task(name): ''' Disable a kapacitor task. name Name of the task to disable. CLI Example: .. code-block:: bash salt '*' kapacitor.disable_task cpu ''' return _run_cmd('kapacitor disable {0}'.format(name))
saltstack/salt
salt/modules/kapacitor.py
define_task
python
def define_task(name, tick_script, task_type='stream', database=None, retention_policy='default', dbrps=None): ''' Define a task. Serves as both create/update. name Name of the task. tick_script Path to the TICK script for the task. Can be a salt:// source. task_type Task type. Defaults to 'stream' dbrps A list of databases and retention policies in "dbname"."rpname" format to fetch data from. For backward compatibility, the value of 'database' and 'retention_policy' will be merged as part of dbrps. .. versionadded:: 2019.2.0 database Which database to fetch data from. retention_policy Which retention policy to fetch data from. Defaults to 'default'. CLI Example: .. code-block:: bash salt '*' kapacitor.define_task cpu salt://kapacitor/cpu.tick database=telegraf ''' if not database and not dbrps: log.error("Providing database name or dbrps is mandatory.") return False if version() < '0.13': cmd = 'kapacitor define -name {0}'.format(name) else: cmd = 'kapacitor define {0}'.format(name) if tick_script.startswith('salt://'): tick_script = __salt__['cp.cache_file'](tick_script, __env__) cmd += ' -tick {0}'.format(tick_script) if task_type: cmd += ' -type {0}'.format(task_type) if not dbrps: dbrps = [] if database and retention_policy: dbrp = '{0}.{1}'.format(database, retention_policy) dbrps.append(dbrp) if dbrps: for dbrp in dbrps: cmd += ' -dbrp {0}'.format(dbrp) return _run_cmd(cmd)
Define a task. Serves as both create/update. name Name of the task. tick_script Path to the TICK script for the task. Can be a salt:// source. task_type Task type. Defaults to 'stream' dbrps A list of databases and retention policies in "dbname"."rpname" format to fetch data from. For backward compatibility, the value of 'database' and 'retention_policy' will be merged as part of dbrps. .. versionadded:: 2019.2.0 database Which database to fetch data from. retention_policy Which retention policy to fetch data from. Defaults to 'default'. CLI Example: .. code-block:: bash salt '*' kapacitor.define_task cpu salt://kapacitor/cpu.tick database=telegraf
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L129-L194
[ "def _run_cmd(cmd):\n '''\n Run a Kapacitor task and return a dictionary of info.\n '''\n ret = {}\n env_vars = {\n 'KAPACITOR_URL': _get_url(),\n 'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'),\n }\n result = __salt__['cmd.run_all'](cmd, env=env_vars)\n\n if result.get('stdout'):\n ret['stdout'] = result['stdout']\n if result.get('stderr'):\n ret['stderr'] = result['stderr']\n ret['success'] = result['retcode'] == 0\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Kapacitor execution module. :configuration: This module accepts connection configuration details either as parameters or as configuration settings in /etc/salt/minion on the relevant minions:: kapacitor.host: 'localhost' kapacitor.port: 9092 .. versionadded:: 2016.11.0 Also protocol and SSL settings could be configured:: kapacitor.unsafe_ssl: 'false' kapacitor.protocol: 'http' .. versionadded:: 2019.2.0 This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt lobs from salt.ext import six import salt.utils.http import salt.utils.json import salt.utils.path from salt.utils.decorators import memoize import logging as logger # Setup the logger log = logger.getLogger(__name__) def __virtual__(): return 'kapacitor' if salt.utils.path.which('kapacitor') else False @memoize def version(): ''' Get the kapacitor version. ''' version = __salt__['pkg.version']('kapacitor') if not version: version = six.string_types(__salt__['config.option']('kapacitor.version', 'latest')) return version def _get_url(): ''' Get the kapacitor URL. ''' protocol = __salt__['config.option']('kapacitor.protocol', 'http') host = __salt__['config.option']('kapacitor.host', 'localhost') port = __salt__['config.option']('kapacitor.port', 9092) return '{0}://{1}:{2}'.format(protocol, host, port) def get_task(name): ''' Get a dict of data on a task. name Name of the task to get information about. CLI Example: .. code-block:: bash salt '*' kapacitor.get_task cpu ''' url = _get_url() if version() < '0.13': task_url = '{0}/task?name={1}'.format(url, name) else: task_url = '{0}/kapacitor/v1/tasks/{1}?skip-format=true'.format(url, name) response = salt.utils.http.query(task_url, status=True) if response['status'] == 404: return None data = salt.utils.json.loads(response['body']) if version() < '0.13': return { 'script': data['TICKscript'], 'type': data['Type'], 'dbrps': data['DBRPs'], 'enabled': data['Enabled'], } return { 'script': data['script'], 'type': data['type'], 'dbrps': data['dbrps'], 'enabled': data['status'] == 'enabled', } def _run_cmd(cmd): ''' Run a Kapacitor task and return a dictionary of info. ''' ret = {} env_vars = { 'KAPACITOR_URL': _get_url(), 'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'), } result = __salt__['cmd.run_all'](cmd, env=env_vars) if result.get('stdout'): ret['stdout'] = result['stdout'] if result.get('stderr'): ret['stderr'] = result['stderr'] ret['success'] = result['retcode'] == 0 return ret def delete_task(name): ''' Delete a kapacitor task. name Name of the task to delete. CLI Example: .. code-block:: bash salt '*' kapacitor.delete_task cpu ''' return _run_cmd('kapacitor delete tasks {0}'.format(name)) def enable_task(name): ''' Enable a kapacitor task. name Name of the task to enable. CLI Example: .. code-block:: bash salt '*' kapacitor.enable_task cpu ''' return _run_cmd('kapacitor enable {0}'.format(name)) def disable_task(name): ''' Disable a kapacitor task. name Name of the task to disable. CLI Example: .. code-block:: bash salt '*' kapacitor.disable_task cpu ''' return _run_cmd('kapacitor disable {0}'.format(name))
saltstack/salt
salt/modules/linux_ip.py
_ip_ifaces
python
def _ip_ifaces(): ''' Parse output from 'ip a' ''' tmp = {} ret = {} if_ = None at_ = None out = __salt__['cmd.run']('ip a') for line in out.splitlines(): if not line.startswith(' '): comps = line.split(':') if_ = comps[1].strip() opts_comps = comps[2].strip().split() flags = opts_comps.pop(0).lstrip('<').rstrip('>').split(',') opts_iter = iter(opts_comps) ret[if_] = { 'flags': flags, 'options': dict(list(zip(opts_iter, opts_iter))) } else: if line.strip().startswith('link'): comps = iter(line.strip().split()) ret[if_]['link_layer'] = dict(list(zip(comps, comps))) elif line.strip().startswith('inet'): comps = line.strip().split() at_ = comps[0] if len(comps) % 2 != 0: last = comps.pop() comps[-1] += ' {0}'.format(last) ifi = iter(comps) ret[if_][at_] = dict(list(zip(ifi, ifi))) else: comps = line.strip().split() ifi = iter(comps) ret[if_][at_].update(dict(list(zip(ifi, ifi)))) return ret
Parse output from 'ip a'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_ip.py#L67-L103
null
# -*- coding: utf-8 -*- ''' The networking module for Non-RH/Deb Linux distros ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to Non-RH/Deb Linux distros ''' if salt.utils.platform.is_windows(): return (False, 'Module linux_ip: Windows systems are not supported.') if __grains__['os_family'] == 'RedHat': return (False, 'Module linux_ip: RedHat systems are not supported.') if __grains__['os_family'] == 'Debian': return (False, 'Module linux_ip: Debian systems are not supported.') if __grains__['os_family'] == 'NILinuxRT': return (False, 'Module linux_ip: NILinuxRT systems are not supported.') if not salt.utils.path.which('ip'): return (False, 'The linux_ip execution module cannot be loaded: ' 'the ip binary is not in the path.') return __virtualname__ def down(iface, iface_type=None): ''' Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ip link set {0} down'.format(iface)) return None def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' ifaces = _ip_ifaces() return ifaces.get(iface) def up(iface, iface_type=None): ''' Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ip link set {0} up'.format(iface)) return None def get_routes(iface=None): ''' Return the current routing table CLI Examples: .. code-block:: bash salt '*' ip.get_routes salt '*' ip.get_routes eth0 ''' routes = _parse_routes() if iface is not None: return routes.get(iface) return routes def _parse_routes(): ''' Parse the contents of ``/proc/net/route`` ''' with salt.utils.files.fopen('/proc/net/route', 'r') as fp_: out = salt.utils.stringutils.to_unicode(fp_.read()) ret = {} for line in out.splitlines(): tmp = {} if not line.strip(): continue if line.startswith('Iface'): continue comps = line.split() tmp['iface'] = comps[0] tmp['destination'] = _hex_to_octets(comps[1]) tmp['gateway'] = _hex_to_octets(comps[2]) tmp['flags'] = _route_flags(int(comps[3])) tmp['refcnt'] = comps[4] tmp['use'] = comps[5] tmp['metric'] = comps[6] tmp['mask'] = _hex_to_octets(comps[7]) tmp['mtu'] = comps[8] tmp['window'] = comps[9] tmp['irtt'] = comps[10] if comps[0] not in ret: ret[comps[0]] = [] ret[comps[0]].append(tmp) return ret def _hex_to_octets(addr): ''' Convert hex fields from /proc/net/route to octects ''' return '{0}:{1}:{2}:{3}'.format( int(addr[6:8], 16), int(addr[4:6], 16), int(addr[2:4], 16), int(addr[0:2], 16), ) def _route_flags(rflags): ''' https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h ''' flags = '' fmap = { 0x0001: 'U', # RTF_UP, route is up 0x0002: 'G', # RTF_GATEWAY, use gateway 0x0004: 'H', # RTF_HOST, target is a host 0x0008: 'R', # RET_REINSTATE, reinstate route for dynamic routing 0x0010: 'D', # RTF_DYNAMIC, dynamically installed by daemon or redirect 0x0020: 'M', # RTF_MODIFIED, modified from routing daemon or redirect 0x00040000: 'A', # RTF_ADDRCONF, installed by addrconf 0x01000000: 'C', # RTF_CACHE, cache entry 0x0200: '!', # RTF_REJECT, reject route } for item in fmap: if rflags & item: flags += fmap[item] return flags
saltstack/salt
salt/modules/linux_ip.py
_parse_routes
python
def _parse_routes(): ''' Parse the contents of ``/proc/net/route`` ''' with salt.utils.files.fopen('/proc/net/route', 'r') as fp_: out = salt.utils.stringutils.to_unicode(fp_.read()) ret = {} for line in out.splitlines(): tmp = {} if not line.strip(): continue if line.startswith('Iface'): continue comps = line.split() tmp['iface'] = comps[0] tmp['destination'] = _hex_to_octets(comps[1]) tmp['gateway'] = _hex_to_octets(comps[2]) tmp['flags'] = _route_flags(int(comps[3])) tmp['refcnt'] = comps[4] tmp['use'] = comps[5] tmp['metric'] = comps[6] tmp['mask'] = _hex_to_octets(comps[7]) tmp['mtu'] = comps[8] tmp['window'] = comps[9] tmp['irtt'] = comps[10] if comps[0] not in ret: ret[comps[0]] = [] ret[comps[0]].append(tmp) return ret
Parse the contents of ``/proc/net/route``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_ip.py#L139-L168
[ "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 to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# -*- coding: utf-8 -*- ''' The networking module for Non-RH/Deb Linux distros ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to Non-RH/Deb Linux distros ''' if salt.utils.platform.is_windows(): return (False, 'Module linux_ip: Windows systems are not supported.') if __grains__['os_family'] == 'RedHat': return (False, 'Module linux_ip: RedHat systems are not supported.') if __grains__['os_family'] == 'Debian': return (False, 'Module linux_ip: Debian systems are not supported.') if __grains__['os_family'] == 'NILinuxRT': return (False, 'Module linux_ip: NILinuxRT systems are not supported.') if not salt.utils.path.which('ip'): return (False, 'The linux_ip execution module cannot be loaded: ' 'the ip binary is not in the path.') return __virtualname__ def down(iface, iface_type=None): ''' Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ip link set {0} down'.format(iface)) return None def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' ifaces = _ip_ifaces() return ifaces.get(iface) def _ip_ifaces(): ''' Parse output from 'ip a' ''' tmp = {} ret = {} if_ = None at_ = None out = __salt__['cmd.run']('ip a') for line in out.splitlines(): if not line.startswith(' '): comps = line.split(':') if_ = comps[1].strip() opts_comps = comps[2].strip().split() flags = opts_comps.pop(0).lstrip('<').rstrip('>').split(',') opts_iter = iter(opts_comps) ret[if_] = { 'flags': flags, 'options': dict(list(zip(opts_iter, opts_iter))) } else: if line.strip().startswith('link'): comps = iter(line.strip().split()) ret[if_]['link_layer'] = dict(list(zip(comps, comps))) elif line.strip().startswith('inet'): comps = line.strip().split() at_ = comps[0] if len(comps) % 2 != 0: last = comps.pop() comps[-1] += ' {0}'.format(last) ifi = iter(comps) ret[if_][at_] = dict(list(zip(ifi, ifi))) else: comps = line.strip().split() ifi = iter(comps) ret[if_][at_].update(dict(list(zip(ifi, ifi)))) return ret def up(iface, iface_type=None): ''' Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ip link set {0} up'.format(iface)) return None def get_routes(iface=None): ''' Return the current routing table CLI Examples: .. code-block:: bash salt '*' ip.get_routes salt '*' ip.get_routes eth0 ''' routes = _parse_routes() if iface is not None: return routes.get(iface) return routes def _hex_to_octets(addr): ''' Convert hex fields from /proc/net/route to octects ''' return '{0}:{1}:{2}:{3}'.format( int(addr[6:8], 16), int(addr[4:6], 16), int(addr[2:4], 16), int(addr[0:2], 16), ) def _route_flags(rflags): ''' https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h ''' flags = '' fmap = { 0x0001: 'U', # RTF_UP, route is up 0x0002: 'G', # RTF_GATEWAY, use gateway 0x0004: 'H', # RTF_HOST, target is a host 0x0008: 'R', # RET_REINSTATE, reinstate route for dynamic routing 0x0010: 'D', # RTF_DYNAMIC, dynamically installed by daemon or redirect 0x0020: 'M', # RTF_MODIFIED, modified from routing daemon or redirect 0x00040000: 'A', # RTF_ADDRCONF, installed by addrconf 0x01000000: 'C', # RTF_CACHE, cache entry 0x0200: '!', # RTF_REJECT, reject route } for item in fmap: if rflags & item: flags += fmap[item] return flags
saltstack/salt
salt/modules/linux_ip.py
_hex_to_octets
python
def _hex_to_octets(addr): ''' Convert hex fields from /proc/net/route to octects ''' return '{0}:{1}:{2}:{3}'.format( int(addr[6:8], 16), int(addr[4:6], 16), int(addr[2:4], 16), int(addr[0:2], 16), )
Convert hex fields from /proc/net/route to octects
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_ip.py#L171-L180
null
# -*- coding: utf-8 -*- ''' The networking module for Non-RH/Deb Linux distros ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to Non-RH/Deb Linux distros ''' if salt.utils.platform.is_windows(): return (False, 'Module linux_ip: Windows systems are not supported.') if __grains__['os_family'] == 'RedHat': return (False, 'Module linux_ip: RedHat systems are not supported.') if __grains__['os_family'] == 'Debian': return (False, 'Module linux_ip: Debian systems are not supported.') if __grains__['os_family'] == 'NILinuxRT': return (False, 'Module linux_ip: NILinuxRT systems are not supported.') if not salt.utils.path.which('ip'): return (False, 'The linux_ip execution module cannot be loaded: ' 'the ip binary is not in the path.') return __virtualname__ def down(iface, iface_type=None): ''' Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ip link set {0} down'.format(iface)) return None def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' ifaces = _ip_ifaces() return ifaces.get(iface) def _ip_ifaces(): ''' Parse output from 'ip a' ''' tmp = {} ret = {} if_ = None at_ = None out = __salt__['cmd.run']('ip a') for line in out.splitlines(): if not line.startswith(' '): comps = line.split(':') if_ = comps[1].strip() opts_comps = comps[2].strip().split() flags = opts_comps.pop(0).lstrip('<').rstrip('>').split(',') opts_iter = iter(opts_comps) ret[if_] = { 'flags': flags, 'options': dict(list(zip(opts_iter, opts_iter))) } else: if line.strip().startswith('link'): comps = iter(line.strip().split()) ret[if_]['link_layer'] = dict(list(zip(comps, comps))) elif line.strip().startswith('inet'): comps = line.strip().split() at_ = comps[0] if len(comps) % 2 != 0: last = comps.pop() comps[-1] += ' {0}'.format(last) ifi = iter(comps) ret[if_][at_] = dict(list(zip(ifi, ifi))) else: comps = line.strip().split() ifi = iter(comps) ret[if_][at_].update(dict(list(zip(ifi, ifi)))) return ret def up(iface, iface_type=None): ''' Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ip link set {0} up'.format(iface)) return None def get_routes(iface=None): ''' Return the current routing table CLI Examples: .. code-block:: bash salt '*' ip.get_routes salt '*' ip.get_routes eth0 ''' routes = _parse_routes() if iface is not None: return routes.get(iface) return routes def _parse_routes(): ''' Parse the contents of ``/proc/net/route`` ''' with salt.utils.files.fopen('/proc/net/route', 'r') as fp_: out = salt.utils.stringutils.to_unicode(fp_.read()) ret = {} for line in out.splitlines(): tmp = {} if not line.strip(): continue if line.startswith('Iface'): continue comps = line.split() tmp['iface'] = comps[0] tmp['destination'] = _hex_to_octets(comps[1]) tmp['gateway'] = _hex_to_octets(comps[2]) tmp['flags'] = _route_flags(int(comps[3])) tmp['refcnt'] = comps[4] tmp['use'] = comps[5] tmp['metric'] = comps[6] tmp['mask'] = _hex_to_octets(comps[7]) tmp['mtu'] = comps[8] tmp['window'] = comps[9] tmp['irtt'] = comps[10] if comps[0] not in ret: ret[comps[0]] = [] ret[comps[0]].append(tmp) return ret def _route_flags(rflags): ''' https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h ''' flags = '' fmap = { 0x0001: 'U', # RTF_UP, route is up 0x0002: 'G', # RTF_GATEWAY, use gateway 0x0004: 'H', # RTF_HOST, target is a host 0x0008: 'R', # RET_REINSTATE, reinstate route for dynamic routing 0x0010: 'D', # RTF_DYNAMIC, dynamically installed by daemon or redirect 0x0020: 'M', # RTF_MODIFIED, modified from routing daemon or redirect 0x00040000: 'A', # RTF_ADDRCONF, installed by addrconf 0x01000000: 'C', # RTF_CACHE, cache entry 0x0200: '!', # RTF_REJECT, reject route } for item in fmap: if rflags & item: flags += fmap[item] return flags
saltstack/salt
salt/modules/linux_ip.py
_route_flags
python
def _route_flags(rflags): ''' https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h ''' flags = '' fmap = { 0x0001: 'U', # RTF_UP, route is up 0x0002: 'G', # RTF_GATEWAY, use gateway 0x0004: 'H', # RTF_HOST, target is a host 0x0008: 'R', # RET_REINSTATE, reinstate route for dynamic routing 0x0010: 'D', # RTF_DYNAMIC, dynamically installed by daemon or redirect 0x0020: 'M', # RTF_MODIFIED, modified from routing daemon or redirect 0x00040000: 'A', # RTF_ADDRCONF, installed by addrconf 0x01000000: 'C', # RTF_CACHE, cache entry 0x0200: '!', # RTF_REJECT, reject route } for item in fmap: if rflags & item: flags += fmap[item] return flags
https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_ip.py#L183-L203
null
# -*- coding: utf-8 -*- ''' The networking module for Non-RH/Deb Linux distros ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to Non-RH/Deb Linux distros ''' if salt.utils.platform.is_windows(): return (False, 'Module linux_ip: Windows systems are not supported.') if __grains__['os_family'] == 'RedHat': return (False, 'Module linux_ip: RedHat systems are not supported.') if __grains__['os_family'] == 'Debian': return (False, 'Module linux_ip: Debian systems are not supported.') if __grains__['os_family'] == 'NILinuxRT': return (False, 'Module linux_ip: NILinuxRT systems are not supported.') if not salt.utils.path.which('ip'): return (False, 'The linux_ip execution module cannot be loaded: ' 'the ip binary is not in the path.') return __virtualname__ def down(iface, iface_type=None): ''' Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ip link set {0} down'.format(iface)) return None def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' ifaces = _ip_ifaces() return ifaces.get(iface) def _ip_ifaces(): ''' Parse output from 'ip a' ''' tmp = {} ret = {} if_ = None at_ = None out = __salt__['cmd.run']('ip a') for line in out.splitlines(): if not line.startswith(' '): comps = line.split(':') if_ = comps[1].strip() opts_comps = comps[2].strip().split() flags = opts_comps.pop(0).lstrip('<').rstrip('>').split(',') opts_iter = iter(opts_comps) ret[if_] = { 'flags': flags, 'options': dict(list(zip(opts_iter, opts_iter))) } else: if line.strip().startswith('link'): comps = iter(line.strip().split()) ret[if_]['link_layer'] = dict(list(zip(comps, comps))) elif line.strip().startswith('inet'): comps = line.strip().split() at_ = comps[0] if len(comps) % 2 != 0: last = comps.pop() comps[-1] += ' {0}'.format(last) ifi = iter(comps) ret[if_][at_] = dict(list(zip(ifi, ifi))) else: comps = line.strip().split() ifi = iter(comps) ret[if_][at_].update(dict(list(zip(ifi, ifi)))) return ret def up(iface, iface_type=None): ''' Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ip link set {0} up'.format(iface)) return None def get_routes(iface=None): ''' Return the current routing table CLI Examples: .. code-block:: bash salt '*' ip.get_routes salt '*' ip.get_routes eth0 ''' routes = _parse_routes() if iface is not None: return routes.get(iface) return routes def _parse_routes(): ''' Parse the contents of ``/proc/net/route`` ''' with salt.utils.files.fopen('/proc/net/route', 'r') as fp_: out = salt.utils.stringutils.to_unicode(fp_.read()) ret = {} for line in out.splitlines(): tmp = {} if not line.strip(): continue if line.startswith('Iface'): continue comps = line.split() tmp['iface'] = comps[0] tmp['destination'] = _hex_to_octets(comps[1]) tmp['gateway'] = _hex_to_octets(comps[2]) tmp['flags'] = _route_flags(int(comps[3])) tmp['refcnt'] = comps[4] tmp['use'] = comps[5] tmp['metric'] = comps[6] tmp['mask'] = _hex_to_octets(comps[7]) tmp['mtu'] = comps[8] tmp['window'] = comps[9] tmp['irtt'] = comps[10] if comps[0] not in ret: ret[comps[0]] = [] ret[comps[0]].append(tmp) return ret def _hex_to_octets(addr): ''' Convert hex fields from /proc/net/route to octects ''' return '{0}:{1}:{2}:{3}'.format( int(addr[6:8], 16), int(addr[4:6], 16), int(addr[2:4], 16), int(addr[0:2], 16), )
saltstack/salt
salt/modules/nilrt_ip.py
_get_state
python
def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc))
Returns the state of connman
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L85-L94
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_technologies
python
def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech
Returns the technologies of connman
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L97-L106
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_services
python
def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv
Returns a list with all connman services
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L109-L117
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_connected
python
def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready'
Verify if a connman service is connected
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L120-L125
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_space_delimited_list
python
def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value)
validate that a value contains one or more space-delimited values
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L128-L140
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_validate_ipv4
python
def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, ''
validate ipv4 values
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L143-L156
[ "def ipv4_addr(addr):\n '''\n Returns True if the IPv4 address (and optional subnet) are valid, otherwise\n returns False.\n '''\n return __ip_addr(addr, socket.AF_INET)\n" ]
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_interface_to_service
python
def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None
returns the coresponding service to given interface if exists, otherwise return None
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L159-L167
[ "def _get_services():\n '''\n Returns a list with all connman services\n '''\n serv = []\n services = pyconnman.ConnManager().get_services()\n for path, _ in services:\n serv.append(six.text_type(path[len(SERVICE_PATH):]))\n return serv\n" ]
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_service_info
python
def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data
return details about given connman service
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L170-L230
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_dns_info
python
def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list
return dns list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L233-L248
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_load_config
python
def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results
Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L261-L281
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_request_mode_info
python
def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal'
return requestmode for given interface
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L284-L303
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_possible_adapter_modes
python
def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes
Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L314-L345
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_static_info
python
def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data
Return information about an interface from config file. :param interface: interface label
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L348-L374
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_base_interface_info
python
def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] }
return base details about given interface
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L377-L414
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_ethercat_interface_info
python
def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information
return details about given ethercat interface
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L417-L425
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_tcpip_interface_info
python
def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information
return details about given tcpip interface
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L428-L452
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_get_interface_info
python
def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface)
return details about given interface
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L455-L464
null
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines() def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
saltstack/salt
salt/modules/nilrt_ip.py
_dict_to_string
python
def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif isinstance(val, list): text = ' '.join([six.text_type(item) for item in val]) ret += six.text_type(key) + ': ' + text + '\n' else: ret += six.text_type(key) + ': ' + six.text_type(val) + '\n' return ret.splitlines()
converts a dictionary object into a list of strings
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L467-L481
[ "def _dict_to_string(dictionary):\n '''\n converts a dictionary object into a list of strings\n '''\n ret = ''\n for key, val in sorted(dictionary.items()):\n if isinstance(val, dict):\n for line in _dict_to_string(val):\n ret += six.text_type(key) + '-' + line + '\\n'\n elif isinstance(val, list):\n text = ' '.join([six.text_type(item) for item in val])\n ret += six.text_type(key) + ': ' + text + '\\n'\n else:\n ret += six.text_type(key) + ': ' + six.text_type(val) + '\\n'\n return ret.splitlines()\n" ]
# -*- coding: utf-8 -*- ''' The networking module for NI Linux Real-Time distro ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time import os import re # Import salt libs import salt.exceptions import salt.utils.files import salt.utils.validate.net # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, configparser from salt.ext import six # pylint: enable=import-error,redefined-builtin,no-name-in-module try: import pyconnman except ImportError: pyconnman = None try: import dbus except ImportError: dbus = None try: import pyiface from pyiface.ifreqioctls import IFF_LOOPBACK, IFF_RUNNING except ImportError: pyiface = None try: from requests.structures import CaseInsensitiveDict except ImportError: CaseInsensitiveDict = None log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'ip' SERVICE_PATH = '/net/connman/service/' INTERFACES_CONFIG = '/var/lib/connman/interfaces.config' NIRTCFG_PATH = '/usr/local/natinst/bin/nirtcfg' INI_FILE = '/etc/natinst/share/ni-rt.ini' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] NIRTCFG_ETHERCAT = 'EtherCAT' def _assume_condition(condition, err): ''' Raise an exception if the condition is false ''' if not condition: raise RuntimeError(err) def __virtual__(): ''' Confine this module to NI Linux Real-Time based distros ''' try: msg = 'The nilrt_ip module could not be loaded: unsupported OS family' _assume_condition(__grains__['os_family'] == 'NILinuxRT', msg) _assume_condition(CaseInsensitiveDict, 'The python package request is not installed') _assume_condition(pyiface, 'The python pyiface package is not installed') if __grains__['lsb_distrib_id'] != 'nilrt': _assume_condition(pyconnman, 'The python package pyconnman is not installed') _assume_condition(dbus, 'The python DBus package is not installed') _assume_condition(_get_state() != 'offline', 'Connman is not running') except RuntimeError as exc: return False, str(exc) return __virtualname__ def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1) return tech def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready' def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: return True, 'space-delimited string' return False, '{0} is not a valid list.\n'.format(value) def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1]) if not salt.utils.validate.net.ipv4_addr(value[2].strip()): return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2]) else: return False, 'Invalid value: {0} for ipv4 option'.format(value) return True, '' def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface'] == iface: return _service return None def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']), 'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address']) } state = service_info.get_property('State') if state == 'ready' or state == 'online': data['up'] = True data['ipv4'] = { 'gateway': '0.0.0.0' } ipv4 = 'IPv4' if service_info.get_property('IPv4')['Method'] == 'manual': ipv4 += '.Configuration' ipv4_info = service_info.get_property(ipv4) for info in ['Method', 'Address', 'Netmask', 'Gateway']: value = ipv4_info.get(info) if value is None: log.warning('Unable to get IPv4 %s for service %s\n', info, service) continue if info == 'Method': info = 'requestmode' if value == 'dhcp': value = 'dhcp_linklocal' elif value in ('manual', 'fixed'): value = 'static' data['ipv4'][info.lower()] = six.text_type(value) ipv6_info = service_info.get_property('IPv6') for info in ['Address', 'Prefix', 'Gateway']: value = ipv6_info.get(info) if value is None: log.warning('Unable to get IPv6 %s for service %s\n', info, service) continue if 'ipv6' not in data: data['ipv6'] = {} data['ipv6'][info.lower()] = [six.text_type(value)] nameservers = [] for nameserver_prop in service_info.get_property('Nameservers'): nameservers.append(six.text_type(nameserver_prop)) data['ipv4']['dns'] = nameservers else: data['up'] = False data['ipv4'] = { 'requestmode': 'disabled' } data['ipv4']['supportedrequestmodes'] = [ 'static', 'dhcp_linklocal', 'disabled' ] return data def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip() if dns not in dns_list: dns_list.append(dns) except IOError: log.warning('Could not get domain\n') return dns_list def _remove_quotes(value): ''' Remove leading and trailing double quotes if they exist. ''' # nirtcfg writes values with quotes if len(value) > 1 and value[0] == value[-1] == '\"': value = value[1:-1] return value def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty string. :param filename: config file. Default is INI_FILE. :return: ''' results = {} if not options: return results with salt.utils.files.fopen(filename, 'r') as config_file: config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict) config_parser.readfp(config_file) for option in options: results[option] = _remove_quotes(config_parser.get(section, option)) \ if config_parser.has_option(section, option) else default_value return results def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only' else: if link_local_enabled == 1: return 'linklocal_only' if link_local_enabled == 0: return 'static' # some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables # when selecting "DHCP or Link Local" from MAX, so return it by default to avoid # having the requestmode "None" because none of the conditions above matched. return 'dhcp_linklocal' def _get_adapter_mode_info(interface): ''' return adaptermode for given interface ''' mode = _load_config(interface, ['mode'])['mode'].lower() return mode if mode in ['disabled', 'ethercat'] else 'tcpip' def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower() sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface)) with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: if line.startswith("DEVTYPE="): uevent_devtype = line.split('=')[1].strip() break for adapter_mode in blacklist: if adapter_mode == '_': continue value = blacklist.get(adapter_mode, {}) if value.get('additional_protocol') and adapter_mode not in protocols: continue if interface not in value['name'] \ and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or (blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype) for iface_type in value['type']): adapter_modes += [adapter_mode] return adapter_modes def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { 'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'], 'requestmode': 'static' }, 'wireless': False } hwaddr_section_number = ''.join(data['hwaddr'].split(':')) if os.path.exists(INTERFACES_CONFIG): information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG) if information['IPv4'] != '': ipv4_information = information['IPv4'].split('/') data['ipv4']['address'] = ipv4_information[0] data['ipv4']['dns'] = information['Nameservers'].split(',') data['ipv4']['netmask'] = ipv4_information[1] data['ipv4']['gateway'] = ipv4_information[2] return data def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget'], 'additional_protocol': False }, 'ethercat': { 'name': ['eth0'], 'type': ['gadget', 'usb', 'wlan'], 'additional_protocol': True }, '_': { 'usb': 'sys', 'gadget': 'uevent', 'wlan': 'uevent' } } return { 'label': interface.name, 'connectionid': interface.name, 'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist), 'adapter_mode': _get_adapter_mode_info(interface.name), 'up': interface.flags & IFF_RUNNING != 0, 'ipv4': { 'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'], 'requestmode': _get_request_mode_info(interface.name) }, 'hwaddr': interface.hwaddr[:-1] } def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address']) base_information['ipv4']['address'] = settings['IP_Address'] base_information['ipv4']['netmask'] = settings['Subnet_Mask'] base_information['ipv4']['gateway'] = settings['Gateway'] base_information['ipv4']['dns'] = [settings['DNS_Address']] elif base_information['up']: base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr) base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask) base_information['ipv4']['gateway'] = '0.0.0.0' base_information['ipv4']['dns'] = _get_dns_info() with salt.utils.files.fopen('/proc/net/route', 'r') as route_file: pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name), re.MULTILINE) match = pattern.search(route_file.read()) iface_gateway_hex = None if not match else match.group(1) if iface_gateway_hex is not None and len(iface_gateway_hex) == 8: base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16)) for i in range(6, -1, -2)]) return base_information def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(interface) return _get_tcpip_interface_info(interface) def _get_info(interface): ''' Return information about an interface if it's associated with a service. :param interface: interface label ''' service = _interface_to_service(interface.name) return _get_service_info(service) def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0] if __grains__['lsb_distrib_id'] == 'nilrt': return {'interfaces': list(map(_get_interface_info, _interfaces))} # filter just the services _interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None] return {'interfaces': list(map(_get_info, _interfaces))} def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state)) if out['retcode'] != 0: msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable', interface, out['stderr']) raise salt.exceptions.CommandExecutionError(msg) return True def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool ''' if __grains__['lsb_distrib_id'] == 'nilrt': return _change_state_legacy(interface, new_state) service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) connected = _connected(service) if (not connected and new_state == 'up') or (connected and new_state == 'down'): service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) try: state = service.connect() if new_state == 'up' else service.disconnect() return state is None except Exception: raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n' .format('enable' if new_state == 'up' else 'disable', service)) return True def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.up interface-label ''' return _change_state(interface, 'up') def enable(interface): ''' Enable the specified interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was enabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.enable interface-label ''' return up(interface) def down(interface, iface_type=None): # pylint: disable=unused-argument ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.down interface-label ''' return _change_state(interface, 'down') def disable(interface): ''' Disable the specified interface Change adapter mode to Disabled. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the service was disabled, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.disable interface-label ''' return down(interface) def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section) raise salt.exceptions.CommandExecutionError(exc_msg) def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :return: True if the settings were applied, otherwise an exception will be thrown. CLI Example: .. code-block:: bash salt '*' ip.set_ethercat interface-label master-id ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', NIRTCFG_ETHERCAT) _save_config(interface, 'MasterID', master_id) if initial_mode != 'ethercat': __salt__['system.set_reboot_required_witnessed']() return True raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') def _restart(interface): ''' Disable and enable an interface ''' disable(interface) enable(interface) def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_dhcp_linklocal_all interface-label ''' if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('dhcp', variant_level=1) ipv4['Address'] = dbus.String('', variant_level=1) ipv4['Netmask'] = dbus.String('', variant_level=1) ipv4['Gateway'] = dbus.String('', variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) service.set_property('Nameservers.Configuration', ['']) # reset nameservers list except Exception as exc: exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.dhcp_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '1') _save_config(interface, 'linklocalenabled', '0') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def set_linklocal_only_all(interface): ''' Configure specified adapter to use linklocal only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.linklocal_only_all interface-label ''' if not __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version') initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '1') if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :return: True if settings were applied successfully. :rtype: bool ''' interface = pyiface.Interface(name=interface) parser = configparser.ConfigParser() if os.path.exists(INTERFACES_CONFIG): try: with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file: parser.readfp(config_file) except configparser.MissingSectionHeaderError: pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = ''.join(hwaddr.split(':')) if not parser.has_section('interface_{0}'.format(hwaddr_section_number)): parser.add_section('interface_{0}'.format(hwaddr_section_number)) ip_address = settings.get('ip', '0.0.0.0') netmask = settings.get('netmask', '0.0.0.0') gateway = settings.get('gateway', '0.0.0.0') dns_servers = settings.get('dns', '') name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number)) parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'. format(ip_address, netmask, gateway)) parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers) parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name) parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr) parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet') with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file: parser.write(config_file) return True def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 address :param str netmask: ipv4 netmask :param str gateway: ipv4 gateway :param str nameservers: list of nameservers servers separated by spaces (Optional) :return: True if the settings were applied, otherwise an exception will be thrown. :rtype: bool CLI Example: .. code-block:: bash salt '*' ip.set_static_all interface-label address netmask gateway nameservers ''' validate, msg = _validate_ipv4([address, netmask, gateway]) if not validate: raise salt.exceptions.CommandExecutionError(msg) if nameservers: validate, msg = _space_delimited_list(nameservers) if not validate: raise salt.exceptions.CommandExecutionError(msg) if not isinstance(nameservers, list): nameservers = nameservers.split(' ') if __grains__['lsb_distrib_id'] == 'nilrt': initial_mode = _get_adapter_mode_info(interface) _save_config(interface, 'Mode', 'TCPIP') _save_config(interface, 'dhcpenabled', '0') _save_config(interface, 'linklocalenabled', '0') _save_config(interface, 'IP_Address', address) _save_config(interface, 'Subnet_Mask', netmask) _save_config(interface, 'Gateway', gateway) if nameservers: _save_config(interface, 'DNS_Address', nameservers[0]) if initial_mode == 'ethercat': __salt__['system.set_reboot_required_witnessed']() else: _restart(interface) return True service = _interface_to_service(interface) if not service: if interface in pyiface.getIfaces(): return _configure_static_interface(interface, **{'ip': address, 'dns': ','.join(nameservers) if nameservers else '', 'netmask': netmask, 'gateway': gateway}) raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface)) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property('IPv4.Configuration') ipv4['Method'] = dbus.String('manual', variant_level=1) ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1) ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1) ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1) try: service.set_property('IPv4.Configuration', ipv4) if nameservers: service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers]) except Exception as exc: exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc) raise salt.exceptions.CommandExecutionError(exc_msg) return True def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: return _dict_to_string(_interface) return None def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if iface_type != 'eth': raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type)) if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp set_dhcp_linklocal_all(iface) elif settings['proto'] != 'static': exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto']) raise salt.exceptions.CommandExecutionError(exc_msg) else: address = settings['ipaddr'] netmask = settings['netmask'] gateway = settings['gateway'] dns = [] for key, val in six.iteritems(settings): if 'dns' in key or 'domain' in key: dns += val set_static_all(iface, address, netmask, gateway, dns) if enabled: up(iface) return get_interface(iface) def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res