repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/cache/localfs.py
updated
def updated(bank, key, cachedir): ''' Return the epoch of the mtime for this cache file ''' key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) if not os.path.isfile(key_file): log.warning('Cache file "%s" does not exist', key_file) return None try: return int(os.path.getmtime(key_file)) except IOError as exc: raise SaltCacheError( 'There was an error reading the mtime for "{0}": {1}'.format( key_file, exc ) )
python
def updated(bank, key, cachedir): ''' Return the epoch of the mtime for this cache file ''' key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) if not os.path.isfile(key_file): log.warning('Cache file "%s" does not exist', key_file) return None try: return int(os.path.getmtime(key_file)) except IOError as exc: raise SaltCacheError( 'There was an error reading the mtime for "{0}": {1}'.format( key_file, exc ) )
[ "def", "updated", "(", "bank", ",", "key", ",", "cachedir", ")", ":", "key_file", "=", "os", ".", "path", ".", "join", "(", "cachedir", ",", "os", ".", "path", ".", "normpath", "(", "bank", ")", ",", "'{0}.p'", ".", "format", "(", "key", ")", ")"...
Return the epoch of the mtime for this cache file
[ "Return", "the", "epoch", "of", "the", "mtime", "for", "this", "cache", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/localfs.py#L103-L118
train
saltstack/salt
salt/cache/localfs.py
flush
def flush(bank, key=None, cachedir=None): ''' Remove the key from the cache bank with all the key content. ''' if cachedir is None: cachedir = __cachedir() try: if key is None: target = os.path.join(cachedir, os.path.normpath(bank)) if not os.path.isdir(target): return False shutil.rmtree(target) else: target = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) if not os.path.isfile(target): return False os.remove(target) except OSError as exc: raise SaltCacheError( 'There was an error removing "{0}": {1}'.format( target, exc ) ) return True
python
def flush(bank, key=None, cachedir=None): ''' Remove the key from the cache bank with all the key content. ''' if cachedir is None: cachedir = __cachedir() try: if key is None: target = os.path.join(cachedir, os.path.normpath(bank)) if not os.path.isdir(target): return False shutil.rmtree(target) else: target = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) if not os.path.isfile(target): return False os.remove(target) except OSError as exc: raise SaltCacheError( 'There was an error removing "{0}": {1}'.format( target, exc ) ) return True
[ "def", "flush", "(", "bank", ",", "key", "=", "None", ",", "cachedir", "=", "None", ")", ":", "if", "cachedir", "is", "None", ":", "cachedir", "=", "__cachedir", "(", ")", "try", ":", "if", "key", "is", "None", ":", "target", "=", "os", ".", "pat...
Remove the key from the cache bank with all the key content.
[ "Remove", "the", "key", "from", "the", "cache", "bank", "with", "all", "the", "key", "content", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/localfs.py#L121-L145
train
saltstack/salt
salt/cache/localfs.py
list_
def list_(bank, cachedir): ''' Return an iterable object containing all entries stored in the specified bank. ''' base = os.path.join(cachedir, os.path.normpath(bank)) if not os.path.isdir(base): return [] try: items = os.listdir(base) except OSError as exc: raise SaltCacheError( 'There was an error accessing directory "{0}": {1}'.format( base, exc ) ) ret = [] for item in items: if item.endswith('.p'): ret.append(item.rstrip(item[-2:])) else: ret.append(item) return ret
python
def list_(bank, cachedir): ''' Return an iterable object containing all entries stored in the specified bank. ''' base = os.path.join(cachedir, os.path.normpath(bank)) if not os.path.isdir(base): return [] try: items = os.listdir(base) except OSError as exc: raise SaltCacheError( 'There was an error accessing directory "{0}": {1}'.format( base, exc ) ) ret = [] for item in items: if item.endswith('.p'): ret.append(item.rstrip(item[-2:])) else: ret.append(item) return ret
[ "def", "list_", "(", "bank", ",", "cachedir", ")", ":", "base", "=", "os", ".", "path", ".", "join", "(", "cachedir", ",", "os", ".", "path", ".", "normpath", "(", "bank", ")", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "base", ")"...
Return an iterable object containing all entries stored in the specified bank.
[ "Return", "an", "iterable", "object", "containing", "all", "entries", "stored", "in", "the", "specified", "bank", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/localfs.py#L148-L169
train
saltstack/salt
salt/cache/localfs.py
contains
def contains(bank, key, cachedir): ''' Checks if the specified bank contains the specified key. ''' if key is None: base = os.path.join(cachedir, os.path.normpath(bank)) return os.path.isdir(base) else: keyfile = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) return os.path.isfile(keyfile)
python
def contains(bank, key, cachedir): ''' Checks if the specified bank contains the specified key. ''' if key is None: base = os.path.join(cachedir, os.path.normpath(bank)) return os.path.isdir(base) else: keyfile = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) return os.path.isfile(keyfile)
[ "def", "contains", "(", "bank", ",", "key", ",", "cachedir", ")", ":", "if", "key", "is", "None", ":", "base", "=", "os", ".", "path", ".", "join", "(", "cachedir", ",", "os", ".", "path", ".", "normpath", "(", "bank", ")", ")", "return", "os", ...
Checks if the specified bank contains the specified key.
[ "Checks", "if", "the", "specified", "bank", "contains", "the", "specified", "key", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/localfs.py#L172-L181
train
saltstack/salt
salt/utils/win_reg.py
key_exists
def key_exists(hive, key, use_32bit_registry=False): ''' Check that the key is found in the registry. This refers to keys and not value/data pairs. To check value/data pairs, use ``value_exists`` Args: hive (str): The hive to connect to key (str): The key to check use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, otherwise False Usage: .. code-block:: python import salt.utils.win_reg as reg reg.key_exists(hive='HKLM', key='SOFTWARE\\Microsoft') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] handle = None try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) return True except pywintypes.error as exc: if exc.winerror == 2: return False raise finally: if handle: win32api.RegCloseKey(handle)
python
def key_exists(hive, key, use_32bit_registry=False): ''' Check that the key is found in the registry. This refers to keys and not value/data pairs. To check value/data pairs, use ``value_exists`` Args: hive (str): The hive to connect to key (str): The key to check use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, otherwise False Usage: .. code-block:: python import salt.utils.win_reg as reg reg.key_exists(hive='HKLM', key='SOFTWARE\\Microsoft') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] handle = None try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) return True except pywintypes.error as exc: if exc.winerror == 2: return False raise finally: if handle: win32api.RegCloseKey(handle)
[ "def", "key_exists", "(", "hive", ",", "key", ",", "use_32bit_registry", "=", "False", ")", ":", "local_hive", "=", "_to_unicode", "(", "hive", ")", "local_key", "=", "_to_unicode", "(", "key", ")", "registry", "=", "Registry", "(", ")", "try", ":", "hke...
Check that the key is found in the registry. This refers to keys and not value/data pairs. To check value/data pairs, use ``value_exists`` Args: hive (str): The hive to connect to key (str): The key to check use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, otherwise False Usage: .. code-block:: python import salt.utils.win_reg as reg reg.key_exists(hive='HKLM', key='SOFTWARE\\Microsoft')
[ "Check", "that", "the", "key", "is", "found", "in", "the", "registry", ".", "This", "refers", "to", "keys", "and", "not", "value", "/", "data", "pairs", ".", "To", "check", "value", "/", "data", "pairs", "use", "value_exists" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L162-L205
train
saltstack/salt
salt/utils/win_reg.py
value_exists
def value_exists(hive, key, vname, use_32bit_registry=False): ''' Check that the value/data pair is found in the registry. .. version-added:: 2018.3.4 Args: hive (str): The hive to connect to key (str): The key to check in vname (str): The name of the value/data pair you're checking use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, otherwise False Usage: .. code-block:: python import salt.utils.win_reg as reg reg.key_exists(hive='HKLM', key='SOFTWARE\\Microsoft') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) except pywintypes.error as exc: if exc.winerror == 2: # The key containing the value/data pair does not exist return False raise try: # RegQueryValueEx returns and accepts unicode data _, _ = win32api.RegQueryValueEx(handle, local_vname) # value/data pair exists return True except pywintypes.error as exc: if exc.winerror == 2 and vname is None: # value/data pair exists but is empty return True else: # value/data pair not found return False finally: win32api.RegCloseKey(handle)
python
def value_exists(hive, key, vname, use_32bit_registry=False): ''' Check that the value/data pair is found in the registry. .. version-added:: 2018.3.4 Args: hive (str): The hive to connect to key (str): The key to check in vname (str): The name of the value/data pair you're checking use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, otherwise False Usage: .. code-block:: python import salt.utils.win_reg as reg reg.key_exists(hive='HKLM', key='SOFTWARE\\Microsoft') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) except pywintypes.error as exc: if exc.winerror == 2: # The key containing the value/data pair does not exist return False raise try: # RegQueryValueEx returns and accepts unicode data _, _ = win32api.RegQueryValueEx(handle, local_vname) # value/data pair exists return True except pywintypes.error as exc: if exc.winerror == 2 and vname is None: # value/data pair exists but is empty return True else: # value/data pair not found return False finally: win32api.RegCloseKey(handle)
[ "def", "value_exists", "(", "hive", ",", "key", ",", "vname", ",", "use_32bit_registry", "=", "False", ")", ":", "local_hive", "=", "_to_unicode", "(", "hive", ")", "local_key", "=", "_to_unicode", "(", "key", ")", "local_vname", "=", "_to_unicode", "(", "...
Check that the value/data pair is found in the registry. .. version-added:: 2018.3.4 Args: hive (str): The hive to connect to key (str): The key to check in vname (str): The name of the value/data pair you're checking use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, otherwise False Usage: .. code-block:: python import salt.utils.win_reg as reg reg.key_exists(hive='HKLM', key='SOFTWARE\\Microsoft')
[ "Check", "that", "the", "value", "/", "data", "pair", "is", "found", "in", "the", "registry", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L208-L266
train
saltstack/salt
salt/utils/win_reg.py
broadcast_change
def broadcast_change(): ''' Refresh the windows environment. .. note:: This will only effect new processes and windows. Services will not see the change until the system restarts. Returns: bool: True if successful, otherwise False Usage: .. code-block:: python import salt.utils.win_reg winreg.broadcast_change() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx _, res = win32gui.SendMessageTimeout( win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 0, win32con.SMTO_ABORTIFHUNG, 5000) return not bool(res)
python
def broadcast_change(): ''' Refresh the windows environment. .. note:: This will only effect new processes and windows. Services will not see the change until the system restarts. Returns: bool: True if successful, otherwise False Usage: .. code-block:: python import salt.utils.win_reg winreg.broadcast_change() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx _, res = win32gui.SendMessageTimeout( win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 0, win32con.SMTO_ABORTIFHUNG, 5000) return not bool(res)
[ "def", "broadcast_change", "(", ")", ":", "# https://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx", "_", ",", "res", "=", "win32gui", ".", "SendMessageTimeout", "(", "win32con", ".", "HWND_BROADCAST", ",", "win32con", ".", "WM_SETTINGCHANGE", ",",...
Refresh the windows environment. .. note:: This will only effect new processes and windows. Services will not see the change until the system restarts. Returns: bool: True if successful, otherwise False Usage: .. code-block:: python import salt.utils.win_reg winreg.broadcast_change()
[ "Refresh", "the", "windows", "environment", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L269-L291
train
saltstack/salt
salt/utils/win_reg.py
list_keys
def list_keys(hive, key=None, use_32bit_registry=False): ''' Enumerates the subkeys in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USERS or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. If a key is not passed, the keys under the hive will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64 bit installations. On 32bit machines this is ignored. Returns: list: A list of keys/subkeys under the hive or key. Usage: .. code-block:: python import salt.utils.win_reg winreg.list_keys(hive='HKLM', key='SOFTWARE\\Microsoft') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] subkeys = [] handle = None try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) for i in range(win32api.RegQueryInfoKey(handle)[0]): subkey = win32api.RegEnumKey(handle, i) if PY2: subkeys.append(_to_mbcs(subkey)) else: subkeys.append(subkey) except Exception: # pylint: disable=E0602 log.debug(r'Cannot find key: %s\%s', hive, key, exc_info=True) return False, r'Cannot find key: {0}\{1}'.format(hive, key) finally: if handle: handle.Close() return subkeys
python
def list_keys(hive, key=None, use_32bit_registry=False): ''' Enumerates the subkeys in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USERS or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. If a key is not passed, the keys under the hive will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64 bit installations. On 32bit machines this is ignored. Returns: list: A list of keys/subkeys under the hive or key. Usage: .. code-block:: python import salt.utils.win_reg winreg.list_keys(hive='HKLM', key='SOFTWARE\\Microsoft') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] subkeys = [] handle = None try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) for i in range(win32api.RegQueryInfoKey(handle)[0]): subkey = win32api.RegEnumKey(handle, i) if PY2: subkeys.append(_to_mbcs(subkey)) else: subkeys.append(subkey) except Exception: # pylint: disable=E0602 log.debug(r'Cannot find key: %s\%s', hive, key, exc_info=True) return False, r'Cannot find key: {0}\{1}'.format(hive, key) finally: if handle: handle.Close() return subkeys
[ "def", "list_keys", "(", "hive", ",", "key", "=", "None", ",", "use_32bit_registry", "=", "False", ")", ":", "local_hive", "=", "_to_unicode", "(", "hive", ")", "local_key", "=", "_to_unicode", "(", "key", ")", "registry", "=", "Registry", "(", ")", "try...
Enumerates the subkeys in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USERS or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. If a key is not passed, the keys under the hive will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64 bit installations. On 32bit machines this is ignored. Returns: list: A list of keys/subkeys under the hive or key. Usage: .. code-block:: python import salt.utils.win_reg winreg.list_keys(hive='HKLM', key='SOFTWARE\\Microsoft')
[ "Enumerates", "the", "subkeys", "in", "a", "registry", "key", "or", "hive", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L294-L357
train
saltstack/salt
salt/utils/win_reg.py
list_values
def list_values(hive, key=None, use_32bit_registry=False, include_default=True): ''' Enumerates the values in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. If a key is not passed, the values under the hive will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64 bit installations. On 32bit machines this is ignored. include_default (bool): Toggle whether to include the '(Default)' value. Returns: list: A list of values under the hive or key. Usage: .. code-block:: python import salt.utils.win_reg winreg.list_values(hive='HKLM', key='SYSTEM\\CurrentControlSet\\Services\\Tcpip') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] handle = None values = list() try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) for i in range(win32api.RegQueryInfoKey(handle)[1]): vname, vdata, vtype = win32api.RegEnumValue(handle, i) if not vname: if not include_default: continue vname = '(Default)' value = {'hive': local_hive, 'key': local_key, 'vname': _to_mbcs(vname), 'vtype': registry.vtype_reverse[vtype], 'success': True} # Only convert text types to unicode if vtype == win32con.REG_MULTI_SZ: value['vdata'] = [_to_mbcs(i) for i in vdata] elif vtype in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]: value['vdata'] = _to_mbcs(vdata) else: value['vdata'] = vdata values.append(value) except Exception as exc: # pylint: disable=E0602 log.debug(r'Cannot find key: %s\%s', hive, key, exc_info=True) return False, r'Cannot find key: {0}\{1}'.format(hive, key) finally: if handle: handle.Close() return values
python
def list_values(hive, key=None, use_32bit_registry=False, include_default=True): ''' Enumerates the values in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. If a key is not passed, the values under the hive will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64 bit installations. On 32bit machines this is ignored. include_default (bool): Toggle whether to include the '(Default)' value. Returns: list: A list of values under the hive or key. Usage: .. code-block:: python import salt.utils.win_reg winreg.list_values(hive='HKLM', key='SYSTEM\\CurrentControlSet\\Services\\Tcpip') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] handle = None values = list() try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) for i in range(win32api.RegQueryInfoKey(handle)[1]): vname, vdata, vtype = win32api.RegEnumValue(handle, i) if not vname: if not include_default: continue vname = '(Default)' value = {'hive': local_hive, 'key': local_key, 'vname': _to_mbcs(vname), 'vtype': registry.vtype_reverse[vtype], 'success': True} # Only convert text types to unicode if vtype == win32con.REG_MULTI_SZ: value['vdata'] = [_to_mbcs(i) for i in vdata] elif vtype in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]: value['vdata'] = _to_mbcs(vdata) else: value['vdata'] = vdata values.append(value) except Exception as exc: # pylint: disable=E0602 log.debug(r'Cannot find key: %s\%s', hive, key, exc_info=True) return False, r'Cannot find key: {0}\{1}'.format(hive, key) finally: if handle: handle.Close() return values
[ "def", "list_values", "(", "hive", ",", "key", "=", "None", ",", "use_32bit_registry", "=", "False", ",", "include_default", "=", "True", ")", ":", "local_hive", "=", "_to_unicode", "(", "hive", ")", "local_key", "=", "_to_unicode", "(", "key", ")", "regis...
Enumerates the values in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. If a key is not passed, the values under the hive will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64 bit installations. On 32bit machines this is ignored. include_default (bool): Toggle whether to include the '(Default)' value. Returns: list: A list of values under the hive or key. Usage: .. code-block:: python import salt.utils.win_reg winreg.list_values(hive='HKLM', key='SYSTEM\\CurrentControlSet\\Services\\Tcpip')
[ "Enumerates", "the", "values", "in", "a", "registry", "key", "or", "hive", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L360-L438
train
saltstack/salt
salt/utils/win_reg.py
read_value
def read_value(hive, key, vname=None, use_32bit_registry=False): r''' Reads a registry value entry or the default value for a key. To read the default value, don't pass ``vname`` Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: dict: A dictionary containing the passed settings as well as the value_data if successful. If unsuccessful, sets success to False. bool: Returns False if the key is not found If vname is not passed: - Returns the first unnamed value (Default) as a string. - Returns none if first unnamed value is empty. Usage: The following will get the value of the ``version`` value name in the ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key .. code-block:: python import salt.utils.win_reg as reg reg.read_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version') Usage: The following will get the default value of the ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key .. code-block:: python import salt.utils.win_reg as reg reg.read_value(hive='HKLM', key='SOFTWARE\\Salt') ''' # If no name is passed, the default value of the key will be returned # The value name is Default # Setup the return array local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) ret = {'hive': local_hive, 'key': local_key, 'vname': local_vname, 'vdata': None, 'success': True} if not vname: ret['vname'] = '(Default)' registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) try: # RegQueryValueEx returns and accepts unicode data vdata, vtype = win32api.RegQueryValueEx(handle, local_vname) if vdata or vdata in [0, '']: # Only convert text types to unicode ret['vtype'] = registry.vtype_reverse[vtype] if vtype == win32con.REG_MULTI_SZ: ret['vdata'] = [_to_mbcs(i) for i in vdata] elif vtype in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]: ret['vdata'] = _to_mbcs(vdata) else: ret['vdata'] = vdata else: ret['comment'] = 'Empty Value' except Exception as exc: if exc.winerror == 2 and vname is None: ret['vdata'] = ('(value not set)') ret['vtype'] = 'REG_SZ' else: msg = 'Cannot find {0} in {1}\\{2}' \ ''.format(local_vname, local_hive, local_key) log.trace(exc) log.trace(msg) ret['comment'] = msg ret['success'] = False except Exception as exc: # pylint: disable=E0602 msg = 'Cannot find key: {0}\\{1}'.format(local_hive, local_key) log.trace(exc) log.trace(msg) ret['comment'] = msg ret['success'] = False return ret
python
def read_value(hive, key, vname=None, use_32bit_registry=False): r''' Reads a registry value entry or the default value for a key. To read the default value, don't pass ``vname`` Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: dict: A dictionary containing the passed settings as well as the value_data if successful. If unsuccessful, sets success to False. bool: Returns False if the key is not found If vname is not passed: - Returns the first unnamed value (Default) as a string. - Returns none if first unnamed value is empty. Usage: The following will get the value of the ``version`` value name in the ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key .. code-block:: python import salt.utils.win_reg as reg reg.read_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version') Usage: The following will get the default value of the ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key .. code-block:: python import salt.utils.win_reg as reg reg.read_value(hive='HKLM', key='SOFTWARE\\Salt') ''' # If no name is passed, the default value of the key will be returned # The value name is Default # Setup the return array local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) ret = {'hive': local_hive, 'key': local_key, 'vname': local_vname, 'vdata': None, 'success': True} if not vname: ret['vname'] = '(Default)' registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) try: # RegQueryValueEx returns and accepts unicode data vdata, vtype = win32api.RegQueryValueEx(handle, local_vname) if vdata or vdata in [0, '']: # Only convert text types to unicode ret['vtype'] = registry.vtype_reverse[vtype] if vtype == win32con.REG_MULTI_SZ: ret['vdata'] = [_to_mbcs(i) for i in vdata] elif vtype in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]: ret['vdata'] = _to_mbcs(vdata) else: ret['vdata'] = vdata else: ret['comment'] = 'Empty Value' except Exception as exc: if exc.winerror == 2 and vname is None: ret['vdata'] = ('(value not set)') ret['vtype'] = 'REG_SZ' else: msg = 'Cannot find {0} in {1}\\{2}' \ ''.format(local_vname, local_hive, local_key) log.trace(exc) log.trace(msg) ret['comment'] = msg ret['success'] = False except Exception as exc: # pylint: disable=E0602 msg = 'Cannot find key: {0}\\{1}'.format(local_hive, local_key) log.trace(exc) log.trace(msg) ret['comment'] = msg ret['success'] = False return ret
[ "def", "read_value", "(", "hive", ",", "key", ",", "vname", "=", "None", ",", "use_32bit_registry", "=", "False", ")", ":", "# If no name is passed, the default value of the key will be returned", "# The value name is Default", "# Setup the return array", "local_hive", "=", ...
r''' Reads a registry value entry or the default value for a key. To read the default value, don't pass ``vname`` Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: dict: A dictionary containing the passed settings as well as the value_data if successful. If unsuccessful, sets success to False. bool: Returns False if the key is not found If vname is not passed: - Returns the first unnamed value (Default) as a string. - Returns none if first unnamed value is empty. Usage: The following will get the value of the ``version`` value name in the ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key .. code-block:: python import salt.utils.win_reg as reg reg.read_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version') Usage: The following will get the default value of the ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key .. code-block:: python import salt.utils.win_reg as reg reg.read_value(hive='HKLM', key='SOFTWARE\\Salt')
[ "r", "Reads", "a", "registry", "value", "entry", "or", "the", "default", "value", "for", "a", "key", ".", "To", "read", "the", "default", "value", "don", "t", "pass", "vname" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L441-L555
train
saltstack/salt
salt/utils/win_reg.py
set_value
def set_value(hive, key, vname=None, vdata=None, vtype='REG_SZ', use_32bit_registry=False, volatile=False): ''' Sets a value in the registry. If ``vname`` is passed, it will be the value for that value name, otherwise it will be the default value for the specified key Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be set. vdata (str, int, list, bytes): The value you'd like to set. If a value name (vname) is passed, this will be the data for that value name. If not, this will be the (Default) value for the key. The type of data this parameter expects is determined by the value type specified in ``vtype``. The correspondence is as follows: - REG_BINARY: Binary data (str in Py2, bytes in Py3) - REG_DWORD: int - REG_EXPAND_SZ: str - REG_MULTI_SZ: list of str - REG_QWORD: int - REG_SZ: str .. note:: When setting REG_BINARY, string data will be converted to binary. You can pass base64 encoded using the ``binascii`` built-in module. Use ``binascii.b2a_base64('your data')`` .. note:: The type for the (Default) value is always REG_SZ and cannot be changed. .. note:: This parameter is optional. If not passed, the Key will be created with no associated item/value pairs. vtype (str): The value type. The possible values of the vtype parameter are indicated above in the description of the vdata parameter. use_32bit_registry (bool): Sets the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. volatile (bool): When this parameter has a value of True, the registry key will be made volatile (i.e. it will not persist beyond a system reset or shutdown). This parameter only has an effect when a key is being created and at no other time. Returns: bool: True if successful, otherwise False Usage: This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in the HKEY_LOCAL_MACHINE hive .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version', vdata='2015.5.2') Usage: This function is strict about the type of vdata. For instance this example will fail because vtype has a value of REG_SZ and vdata has a type of int (as opposed to str as expected). .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata=1.2) Usage: In this next example vdata is properly quoted and should succeed. .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata='1.2') Usage: This is an example of using vtype REG_BINARY. Both ``set_value`` commands will set the same value ``Salty Test`` .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data', vdata='Salty Test', vtype='REG_BINARY') import binascii bin_data = binascii.b2a_base64('Salty Test') winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data_encoded', vdata=bin_data, vtype='REG_BINARY') Usage: An example using vtype REG_MULTI_SZ is as follows: .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='list_data', vdata=['Salt', 'is', 'great'], vtype='REG_MULTI_SZ') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) local_vtype = _to_unicode(vtype) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) vtype_value = registry.vtype[local_vtype] access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS local_vdata = cast_vdata(vdata=vdata, vtype=local_vtype) if volatile: create_options = registry.opttype['REG_OPTION_VOLATILE'] else: create_options = registry.opttype['REG_OPTION_NON_VOLATILE'] handle = None try: handle, _ = win32api.RegCreateKeyEx(hkey, local_key, access_mask, Options=create_options) win32api.RegSetValueEx(handle, local_vname, 0, vtype_value, local_vdata) win32api.RegFlushKey(handle) broadcast_change() return True except (win32api.error, SystemError, ValueError, TypeError): # pylint: disable=E0602 log.exception('Encountered error setting registry value') return False finally: if handle: win32api.RegCloseKey(handle)
python
def set_value(hive, key, vname=None, vdata=None, vtype='REG_SZ', use_32bit_registry=False, volatile=False): ''' Sets a value in the registry. If ``vname`` is passed, it will be the value for that value name, otherwise it will be the default value for the specified key Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be set. vdata (str, int, list, bytes): The value you'd like to set. If a value name (vname) is passed, this will be the data for that value name. If not, this will be the (Default) value for the key. The type of data this parameter expects is determined by the value type specified in ``vtype``. The correspondence is as follows: - REG_BINARY: Binary data (str in Py2, bytes in Py3) - REG_DWORD: int - REG_EXPAND_SZ: str - REG_MULTI_SZ: list of str - REG_QWORD: int - REG_SZ: str .. note:: When setting REG_BINARY, string data will be converted to binary. You can pass base64 encoded using the ``binascii`` built-in module. Use ``binascii.b2a_base64('your data')`` .. note:: The type for the (Default) value is always REG_SZ and cannot be changed. .. note:: This parameter is optional. If not passed, the Key will be created with no associated item/value pairs. vtype (str): The value type. The possible values of the vtype parameter are indicated above in the description of the vdata parameter. use_32bit_registry (bool): Sets the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. volatile (bool): When this parameter has a value of True, the registry key will be made volatile (i.e. it will not persist beyond a system reset or shutdown). This parameter only has an effect when a key is being created and at no other time. Returns: bool: True if successful, otherwise False Usage: This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in the HKEY_LOCAL_MACHINE hive .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version', vdata='2015.5.2') Usage: This function is strict about the type of vdata. For instance this example will fail because vtype has a value of REG_SZ and vdata has a type of int (as opposed to str as expected). .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata=1.2) Usage: In this next example vdata is properly quoted and should succeed. .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata='1.2') Usage: This is an example of using vtype REG_BINARY. Both ``set_value`` commands will set the same value ``Salty Test`` .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data', vdata='Salty Test', vtype='REG_BINARY') import binascii bin_data = binascii.b2a_base64('Salty Test') winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data_encoded', vdata=bin_data, vtype='REG_BINARY') Usage: An example using vtype REG_MULTI_SZ is as follows: .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='list_data', vdata=['Salt', 'is', 'great'], vtype='REG_MULTI_SZ') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) local_vtype = _to_unicode(vtype) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) vtype_value = registry.vtype[local_vtype] access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS local_vdata = cast_vdata(vdata=vdata, vtype=local_vtype) if volatile: create_options = registry.opttype['REG_OPTION_VOLATILE'] else: create_options = registry.opttype['REG_OPTION_NON_VOLATILE'] handle = None try: handle, _ = win32api.RegCreateKeyEx(hkey, local_key, access_mask, Options=create_options) win32api.RegSetValueEx(handle, local_vname, 0, vtype_value, local_vdata) win32api.RegFlushKey(handle) broadcast_change() return True except (win32api.error, SystemError, ValueError, TypeError): # pylint: disable=E0602 log.exception('Encountered error setting registry value') return False finally: if handle: win32api.RegCloseKey(handle)
[ "def", "set_value", "(", "hive", ",", "key", ",", "vname", "=", "None", ",", "vdata", "=", "None", ",", "vtype", "=", "'REG_SZ'", ",", "use_32bit_registry", "=", "False", ",", "volatile", "=", "False", ")", ":", "local_hive", "=", "_to_unicode", "(", "...
Sets a value in the registry. If ``vname`` is passed, it will be the value for that value name, otherwise it will be the default value for the specified key Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be set. vdata (str, int, list, bytes): The value you'd like to set. If a value name (vname) is passed, this will be the data for that value name. If not, this will be the (Default) value for the key. The type of data this parameter expects is determined by the value type specified in ``vtype``. The correspondence is as follows: - REG_BINARY: Binary data (str in Py2, bytes in Py3) - REG_DWORD: int - REG_EXPAND_SZ: str - REG_MULTI_SZ: list of str - REG_QWORD: int - REG_SZ: str .. note:: When setting REG_BINARY, string data will be converted to binary. You can pass base64 encoded using the ``binascii`` built-in module. Use ``binascii.b2a_base64('your data')`` .. note:: The type for the (Default) value is always REG_SZ and cannot be changed. .. note:: This parameter is optional. If not passed, the Key will be created with no associated item/value pairs. vtype (str): The value type. The possible values of the vtype parameter are indicated above in the description of the vdata parameter. use_32bit_registry (bool): Sets the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. volatile (bool): When this parameter has a value of True, the registry key will be made volatile (i.e. it will not persist beyond a system reset or shutdown). This parameter only has an effect when a key is being created and at no other time. Returns: bool: True if successful, otherwise False Usage: This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in the HKEY_LOCAL_MACHINE hive .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version', vdata='2015.5.2') Usage: This function is strict about the type of vdata. For instance this example will fail because vtype has a value of REG_SZ and vdata has a type of int (as opposed to str as expected). .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata=1.2) Usage: In this next example vdata is properly quoted and should succeed. .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata='1.2') Usage: This is an example of using vtype REG_BINARY. Both ``set_value`` commands will set the same value ``Salty Test`` .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data', vdata='Salty Test', vtype='REG_BINARY') import binascii bin_data = binascii.b2a_base64('Salty Test') winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data_encoded', vdata=bin_data, vtype='REG_BINARY') Usage: An example using vtype REG_MULTI_SZ is as follows: .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='list_data', vdata=['Salt', 'is', 'great'], vtype='REG_MULTI_SZ')
[ "Sets", "a", "value", "in", "the", "registry", ".", "If", "vname", "is", "passed", "it", "will", "be", "the", "value", "for", "that", "value", "name", "otherwise", "it", "will", "be", "the", "default", "value", "for", "the", "specified", "key" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L558-L719
train
saltstack/salt
salt/utils/win_reg.py
cast_vdata
def cast_vdata(vdata=None, vtype='REG_SZ'): ''' Cast the ``vdata` value to the appropriate data type for the registry type specified in ``vtype`` Args: vdata (str, int, list, bytes): The data to cast vtype (str): The type of data to be written to the registry. Must be one of the following: - REG_BINARY - REG_DWORD - REG_EXPAND_SZ - REG_MULTI_SZ - REG_QWORD - REG_SZ Returns: The vdata cast to the appropriate type. Will be unicode string, binary, list of unicode strings, or int Usage: .. code-block:: python import salt.utils.win_reg winreg.cast_vdata(vdata='This is the string', vtype='REG_SZ') ''' # Check data type and cast to expected type # int will automatically become long on 64bit numbers # https://www.python.org/dev/peps/pep-0237/ registry = Registry() vtype_value = registry.vtype[vtype] # String Types to Unicode if vtype_value in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]: return _to_unicode(vdata) # Don't touch binary... if it's binary elif vtype_value == win32con.REG_BINARY: if isinstance(vdata, six.text_type): # Unicode data must be encoded return vdata.encode('utf-8') return vdata # Make sure REG_MULTI_SZ is a list of strings elif vtype_value == win32con.REG_MULTI_SZ: return [_to_unicode(i) for i in vdata] # Make sure REG_QWORD is a 64 bit integer elif vtype_value == win32con.REG_QWORD: return vdata if six.PY3 else long(vdata) # pylint: disable=incompatible-py3-code,undefined-variable # Everything else is int else: return int(vdata)
python
def cast_vdata(vdata=None, vtype='REG_SZ'): ''' Cast the ``vdata` value to the appropriate data type for the registry type specified in ``vtype`` Args: vdata (str, int, list, bytes): The data to cast vtype (str): The type of data to be written to the registry. Must be one of the following: - REG_BINARY - REG_DWORD - REG_EXPAND_SZ - REG_MULTI_SZ - REG_QWORD - REG_SZ Returns: The vdata cast to the appropriate type. Will be unicode string, binary, list of unicode strings, or int Usage: .. code-block:: python import salt.utils.win_reg winreg.cast_vdata(vdata='This is the string', vtype='REG_SZ') ''' # Check data type and cast to expected type # int will automatically become long on 64bit numbers # https://www.python.org/dev/peps/pep-0237/ registry = Registry() vtype_value = registry.vtype[vtype] # String Types to Unicode if vtype_value in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]: return _to_unicode(vdata) # Don't touch binary... if it's binary elif vtype_value == win32con.REG_BINARY: if isinstance(vdata, six.text_type): # Unicode data must be encoded return vdata.encode('utf-8') return vdata # Make sure REG_MULTI_SZ is a list of strings elif vtype_value == win32con.REG_MULTI_SZ: return [_to_unicode(i) for i in vdata] # Make sure REG_QWORD is a 64 bit integer elif vtype_value == win32con.REG_QWORD: return vdata if six.PY3 else long(vdata) # pylint: disable=incompatible-py3-code,undefined-variable # Everything else is int else: return int(vdata)
[ "def", "cast_vdata", "(", "vdata", "=", "None", ",", "vtype", "=", "'REG_SZ'", ")", ":", "# Check data type and cast to expected type", "# int will automatically become long on 64bit numbers", "# https://www.python.org/dev/peps/pep-0237/", "registry", "=", "Registry", "(", ")",...
Cast the ``vdata` value to the appropriate data type for the registry type specified in ``vtype`` Args: vdata (str, int, list, bytes): The data to cast vtype (str): The type of data to be written to the registry. Must be one of the following: - REG_BINARY - REG_DWORD - REG_EXPAND_SZ - REG_MULTI_SZ - REG_QWORD - REG_SZ Returns: The vdata cast to the appropriate type. Will be unicode string, binary, list of unicode strings, or int Usage: .. code-block:: python import salt.utils.win_reg winreg.cast_vdata(vdata='This is the string', vtype='REG_SZ')
[ "Cast", "the", "vdata", "value", "to", "the", "appropriate", "data", "type", "for", "the", "registry", "type", "specified", "in", "vtype" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L722-L777
train
saltstack/salt
salt/utils/win_reg.py
delete_key_recursive
def delete_key_recursive(hive, key, use_32bit_registry=False): ''' .. versionadded:: 2015.5.4 Delete a registry key to include all subkeys and value/data pairs. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key to remove (looks like a path) use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: dict: A dictionary listing the keys that deleted successfully as well as those that failed to delete. Usage: The following example will remove ``salt`` and all its subkeys from the ``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``: .. code-block:: python import salt.utils.win_reg winreg.delete_key_recursive(hive='HKLM', key='SOFTWARE\\DeleteMe') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) # Instantiate the registry object registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) key_path = local_key access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS if not key_exists(local_hive, local_key, use_32bit_registry): return False if (len(key) > 1) and (key.count('\\', 1) < registry.subkey_slash_check[hkey]): log.error( 'Hive:%s Key:%s; key is too close to root, not safe to remove', hive, key ) return False # Functions for traversing the registry tree def _subkeys(_key): ''' Enumerate keys ''' i = 0 while True: try: subkey = win32api.RegEnumKey(_key, i) yield _to_mbcs(subkey) i += 1 except Exception: # pylint: disable=E0602 break def _traverse_registry_tree(_hkey, _keypath, _ret, _access_mask): ''' Traverse the registry tree i.e. dive into the tree ''' _key = win32api.RegOpenKeyEx(_hkey, _keypath, 0, _access_mask) for subkeyname in _subkeys(_key): subkeypath = '{0}\\{1}'.format(_keypath, subkeyname) _ret = _traverse_registry_tree(_hkey, subkeypath, _ret, access_mask) _ret.append(subkeypath) return _ret # Get a reverse list of registry keys to be deleted key_list = [] key_list = _traverse_registry_tree(hkey, key_path, key_list, access_mask) # Add the top level key last, all subkeys must be deleted first key_list.append(key_path) ret = {'Deleted': [], 'Failed': []} # Delete all sub_keys for sub_key_path in key_list: try: key_handle = win32api.RegOpenKeyEx(hkey, sub_key_path, 0, access_mask) win32api.RegDeleteKey(key_handle, '') ret['Deleted'].append(r'{0}\{1}'.format(hive, sub_key_path)) except WindowsError as exc: # pylint: disable=E0602 log.error(exc, exc_info=True) ret['Failed'].append(r'{0}\{1} {2}'.format(hive, sub_key_path, exc)) broadcast_change() return ret
python
def delete_key_recursive(hive, key, use_32bit_registry=False): ''' .. versionadded:: 2015.5.4 Delete a registry key to include all subkeys and value/data pairs. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key to remove (looks like a path) use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: dict: A dictionary listing the keys that deleted successfully as well as those that failed to delete. Usage: The following example will remove ``salt`` and all its subkeys from the ``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``: .. code-block:: python import salt.utils.win_reg winreg.delete_key_recursive(hive='HKLM', key='SOFTWARE\\DeleteMe') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) # Instantiate the registry object registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) key_path = local_key access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS if not key_exists(local_hive, local_key, use_32bit_registry): return False if (len(key) > 1) and (key.count('\\', 1) < registry.subkey_slash_check[hkey]): log.error( 'Hive:%s Key:%s; key is too close to root, not safe to remove', hive, key ) return False # Functions for traversing the registry tree def _subkeys(_key): ''' Enumerate keys ''' i = 0 while True: try: subkey = win32api.RegEnumKey(_key, i) yield _to_mbcs(subkey) i += 1 except Exception: # pylint: disable=E0602 break def _traverse_registry_tree(_hkey, _keypath, _ret, _access_mask): ''' Traverse the registry tree i.e. dive into the tree ''' _key = win32api.RegOpenKeyEx(_hkey, _keypath, 0, _access_mask) for subkeyname in _subkeys(_key): subkeypath = '{0}\\{1}'.format(_keypath, subkeyname) _ret = _traverse_registry_tree(_hkey, subkeypath, _ret, access_mask) _ret.append(subkeypath) return _ret # Get a reverse list of registry keys to be deleted key_list = [] key_list = _traverse_registry_tree(hkey, key_path, key_list, access_mask) # Add the top level key last, all subkeys must be deleted first key_list.append(key_path) ret = {'Deleted': [], 'Failed': []} # Delete all sub_keys for sub_key_path in key_list: try: key_handle = win32api.RegOpenKeyEx(hkey, sub_key_path, 0, access_mask) win32api.RegDeleteKey(key_handle, '') ret['Deleted'].append(r'{0}\{1}'.format(hive, sub_key_path)) except WindowsError as exc: # pylint: disable=E0602 log.error(exc, exc_info=True) ret['Failed'].append(r'{0}\{1} {2}'.format(hive, sub_key_path, exc)) broadcast_change() return ret
[ "def", "delete_key_recursive", "(", "hive", ",", "key", ",", "use_32bit_registry", "=", "False", ")", ":", "local_hive", "=", "_to_unicode", "(", "hive", ")", "local_key", "=", "_to_unicode", "(", "key", ")", "# Instantiate the registry object", "registry", "=", ...
.. versionadded:: 2015.5.4 Delete a registry key to include all subkeys and value/data pairs. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key to remove (looks like a path) use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: dict: A dictionary listing the keys that deleted successfully as well as those that failed to delete. Usage: The following example will remove ``salt`` and all its subkeys from the ``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``: .. code-block:: python import salt.utils.win_reg winreg.delete_key_recursive(hive='HKLM', key='SOFTWARE\\DeleteMe')
[ "..", "versionadded", "::", "2015", ".", "5", ".", "4" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L780-L887
train
saltstack/salt
salt/utils/win_reg.py
delete_value
def delete_value(hive, key, vname=None, use_32bit_registry=False): ''' Delete a registry value entry or the default value for a key. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be deleted. use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Return: bool: True if successful, otherwise False Usage: .. code-block:: python import salt.utils.win_reg winreg.delete_value(hive='HKLM', key='SOFTWARE\\SaltTest', vname='version') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS handle = None try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) win32api.RegDeleteValue(handle, local_vname) broadcast_change() return True except Exception as exc: # pylint: disable=E0602 if exc.winerror == 2: return None else: log.error(exc, exc_info=True) log.error('Hive: %s', local_hive) log.error('Key: %s', local_key) log.error('ValueName: %s', local_vname) log.error('32bit Reg: %s', use_32bit_registry) return False finally: if handle: win32api.RegCloseKey(handle)
python
def delete_value(hive, key, vname=None, use_32bit_registry=False): ''' Delete a registry value entry or the default value for a key. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be deleted. use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Return: bool: True if successful, otherwise False Usage: .. code-block:: python import salt.utils.win_reg winreg.delete_value(hive='HKLM', key='SOFTWARE\\SaltTest', vname='version') ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS handle = None try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) win32api.RegDeleteValue(handle, local_vname) broadcast_change() return True except Exception as exc: # pylint: disable=E0602 if exc.winerror == 2: return None else: log.error(exc, exc_info=True) log.error('Hive: %s', local_hive) log.error('Key: %s', local_key) log.error('ValueName: %s', local_vname) log.error('32bit Reg: %s', use_32bit_registry) return False finally: if handle: win32api.RegCloseKey(handle)
[ "def", "delete_value", "(", "hive", ",", "key", ",", "vname", "=", "None", ",", "use_32bit_registry", "=", "False", ")", ":", "local_hive", "=", "_to_unicode", "(", "hive", ")", "local_key", "=", "_to_unicode", "(", "key", ")", "local_vname", "=", "_to_uni...
Delete a registry value entry or the default value for a key. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be deleted. use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Return: bool: True if successful, otherwise False Usage: .. code-block:: python import salt.utils.win_reg winreg.delete_value(hive='HKLM', key='SOFTWARE\\SaltTest', vname='version')
[ "Delete", "a", "registry", "value", "entry", "or", "the", "default", "value", "for", "a", "key", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_reg.py#L890-L955
train
saltstack/salt
salt/modules/at_solaris.py
atq
def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] res = __salt__['cmd.run_all']('atq') if res['retcode'] > 0: return {'error': res['stderr']} # No jobs so return if res['stdout'] == 'no files in queue.': return {'jobs': jobs} # Jobs created with at.at() will use the following # comment to denote a tagged job. job_kw_regex = re.compile(r'^### SALT: (\w+)') # Split each job into a dictionary and handle # pulling out tags or only listing jobs with a certain # tag for line in res['stdout'].splitlines(): job_tag = '' # skip header if line.startswith(' Rank'): continue # parse job output tmp = line.split() timestr = ' '.join(tmp[1:5]) job = tmp[6] specs = datetime.datetime( *(time.strptime(timestr, '%b %d, %Y %H:%M')[0:5]) ).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[5]) # make sure job is str job = six.text_type(job) # search for any tags atjob_file = '/var/spool/cron/atjobs/{job}'.format( job=job ) if __salt__['file.file_exists'](atjob_file): with salt.utils.files.fopen(atjob_file, 'r') as atjob: for line in atjob: line = salt.utils.stringutils.to_unicode(line) tmp = job_kw_regex.match(line) if tmp: job_tag = tmp.groups()[0] # filter on tags if not tag: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) elif tag and tag in [job_tag, job]: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) return {'jobs': jobs}
python
def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] res = __salt__['cmd.run_all']('atq') if res['retcode'] > 0: return {'error': res['stderr']} # No jobs so return if res['stdout'] == 'no files in queue.': return {'jobs': jobs} # Jobs created with at.at() will use the following # comment to denote a tagged job. job_kw_regex = re.compile(r'^### SALT: (\w+)') # Split each job into a dictionary and handle # pulling out tags or only listing jobs with a certain # tag for line in res['stdout'].splitlines(): job_tag = '' # skip header if line.startswith(' Rank'): continue # parse job output tmp = line.split() timestr = ' '.join(tmp[1:5]) job = tmp[6] specs = datetime.datetime( *(time.strptime(timestr, '%b %d, %Y %H:%M')[0:5]) ).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[5]) # make sure job is str job = six.text_type(job) # search for any tags atjob_file = '/var/spool/cron/atjobs/{job}'.format( job=job ) if __salt__['file.file_exists'](atjob_file): with salt.utils.files.fopen(atjob_file, 'r') as atjob: for line in atjob: line = salt.utils.stringutils.to_unicode(line) tmp = job_kw_regex.match(line) if tmp: job_tag = tmp.groups()[0] # filter on tags if not tag: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) elif tag and tag in [job_tag, job]: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) return {'jobs': jobs}
[ "def", "atq", "(", "tag", "=", "None", ")", ":", "jobs", "=", "[", "]", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'atq'", ")", "if", "res", "[", "'retcode'", "]", ">", "0", ":", "return", "{", "'error'", ":", "res", "[", "'stderr'"...
List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number]
[ "List", "all", "queued", "and", "running", "jobs", "or", "only", "those", "with", "an", "optional", "tag", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at_solaris.py#L50-L121
train
saltstack/salt
salt/modules/at_solaris.py
atrm
def atrm(*args): ''' Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag] ''' if not args: return {'jobs': {'removed': [], 'tag': None}} if args[0] == 'all': if len(args) > 1: opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': args[1]}} else: opts = list(list(map(str, [j['job'] for j in atq()['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': None}} else: opts = list(list(map(str, [i['job'] for i in atq()['jobs'] if i['job'] in args]))) ret = {'jobs': {'removed': opts, 'tag': None}} # call atrm for each job in ret['jobs']['removed'] for job in ret['jobs']['removed']: res_job = __salt__['cmd.run_all']('atrm {job}'.format( job=job )) if res_job['retcode'] > 0: if 'failed' not in ret['jobs']: ret['jobs']['failed'] = {} ret['jobs']['failed'][job] = res_job['stderr'] # remove failed from list if 'failed' in ret['jobs']: for job in ret['jobs']['failed']: ret['jobs']['removed'].remove(job) return ret
python
def atrm(*args): ''' Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag] ''' if not args: return {'jobs': {'removed': [], 'tag': None}} if args[0] == 'all': if len(args) > 1: opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': args[1]}} else: opts = list(list(map(str, [j['job'] for j in atq()['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': None}} else: opts = list(list(map(str, [i['job'] for i in atq()['jobs'] if i['job'] in args]))) ret = {'jobs': {'removed': opts, 'tag': None}} # call atrm for each job in ret['jobs']['removed'] for job in ret['jobs']['removed']: res_job = __salt__['cmd.run_all']('atrm {job}'.format( job=job )) if res_job['retcode'] > 0: if 'failed' not in ret['jobs']: ret['jobs']['failed'] = {} ret['jobs']['failed'][job] = res_job['stderr'] # remove failed from list if 'failed' in ret['jobs']: for job in ret['jobs']['failed']: ret['jobs']['removed'].remove(job) return ret
[ "def", "atrm", "(", "*", "args", ")", ":", "if", "not", "args", ":", "return", "{", "'jobs'", ":", "{", "'removed'", ":", "[", "]", ",", "'tag'", ":", "None", "}", "}", "if", "args", "[", "0", "]", "==", "'all'", ":", "if", "len", "(", "args"...
Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag]
[ "Remove", "jobs", "from", "the", "queue", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at_solaris.py#L124-L167
train
saltstack/salt
salt/modules/at_solaris.py
at
def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim ''' # check args if len(args) < 2: return {'jobs': []} # build job if 'tag' in kwargs: stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:])) else: stdin = ' '.join(args[1:]) cmd_kwargs = {'stdin': stdin, 'python_shell': False} if 'runas' in kwargs: cmd_kwargs['runas'] = kwargs['runas'] res = __salt__['cmd.run_all']('at "{timespec}"'.format( timespec=args[0] ), **cmd_kwargs) # verify job creation if res['retcode'] > 0: if 'bad time specification' in res['stderr']: return {'jobs': [], 'error': 'invalid timespec'} return {'jobs': [], 'error': res['stderr']} else: jobid = res['stderr'].splitlines()[1] jobid = six.text_type(jobid.split()[1]) return atq(jobid)
python
def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim ''' # check args if len(args) < 2: return {'jobs': []} # build job if 'tag' in kwargs: stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:])) else: stdin = ' '.join(args[1:]) cmd_kwargs = {'stdin': stdin, 'python_shell': False} if 'runas' in kwargs: cmd_kwargs['runas'] = kwargs['runas'] res = __salt__['cmd.run_all']('at "{timespec}"'.format( timespec=args[0] ), **cmd_kwargs) # verify job creation if res['retcode'] > 0: if 'bad time specification' in res['stderr']: return {'jobs': [], 'error': 'invalid timespec'} return {'jobs': [], 'error': res['stderr']} else: jobid = res['stderr'].splitlines()[1] jobid = six.text_type(jobid.split()[1]) return atq(jobid)
[ "def", "at", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=C0103", "# check args", "if", "len", "(", "args", ")", "<", "2", ":", "return", "{", "'jobs'", ":", "[", "]", "}", "# build job", "if", "'tag'", "in", "kwargs", ":",...
Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim
[ "Add", "a", "job", "to", "the", "queue", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at_solaris.py#L170-L211
train
saltstack/salt
salt/modules/at_solaris.py
atc
def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' atjob_file = '/var/spool/cron/atjobs/{job}'.format( job=jobid ) if __salt__['file.file_exists'](atjob_file): with salt.utils.files.fopen(atjob_file, 'r') as rfh: return ''.join([salt.utils.stringutils.to_unicode(x) for x in rfh.readlines()]) else: return {'error': 'invalid job id \'{0}\''.format(jobid)}
python
def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' atjob_file = '/var/spool/cron/atjobs/{job}'.format( job=jobid ) if __salt__['file.file_exists'](atjob_file): with salt.utils.files.fopen(atjob_file, 'r') as rfh: return ''.join([salt.utils.stringutils.to_unicode(x) for x in rfh.readlines()]) else: return {'error': 'invalid job id \'{0}\''.format(jobid)}
[ "def", "atc", "(", "jobid", ")", ":", "atjob_file", "=", "'/var/spool/cron/atjobs/{job}'", ".", "format", "(", "job", "=", "jobid", ")", "if", "__salt__", "[", "'file.file_exists'", "]", "(", "atjob_file", ")", ":", "with", "salt", ".", "utils", ".", "file...
Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid>
[ "Print", "the", "at", "(", "1", ")", "script", "that", "will", "run", "for", "the", "passed", "job", "id", ".", "This", "is", "mostly", "for", "debugging", "so", "the", "output", "will", "just", "be", "text", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at_solaris.py#L214-L235
train
saltstack/salt
salt/modules/ssh.py
_refine_enc
def _refine_enc(enc): ''' Return the properly formatted ssh value for the authorized encryption key type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string if using higher enc. If the type is not found, raise CommandExecutionError. ''' rsa = ['r', 'rsa', 'ssh-rsa'] dss = ['d', 'dsa', 'dss', 'ssh-dss'] ecdsa = ['e', 'ecdsa', 'ecdsa-sha2-nistp521', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp256'] ed25519 = ['ed25519', 'ssh-ed25519'] if enc in rsa: return 'ssh-rsa' elif enc in dss: return 'ssh-dss' elif enc in ecdsa: # ecdsa defaults to ecdsa-sha2-nistp256 # otherwise enc string is actual encoding string if enc in ['e', 'ecdsa']: return 'ecdsa-sha2-nistp256' return enc elif enc in ed25519: return 'ssh-ed25519' else: raise CommandExecutionError( 'Incorrect encryption key type \'{0}\'.'.format(enc) )
python
def _refine_enc(enc): ''' Return the properly formatted ssh value for the authorized encryption key type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string if using higher enc. If the type is not found, raise CommandExecutionError. ''' rsa = ['r', 'rsa', 'ssh-rsa'] dss = ['d', 'dsa', 'dss', 'ssh-dss'] ecdsa = ['e', 'ecdsa', 'ecdsa-sha2-nistp521', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp256'] ed25519 = ['ed25519', 'ssh-ed25519'] if enc in rsa: return 'ssh-rsa' elif enc in dss: return 'ssh-dss' elif enc in ecdsa: # ecdsa defaults to ecdsa-sha2-nistp256 # otherwise enc string is actual encoding string if enc in ['e', 'ecdsa']: return 'ecdsa-sha2-nistp256' return enc elif enc in ed25519: return 'ssh-ed25519' else: raise CommandExecutionError( 'Incorrect encryption key type \'{0}\'.'.format(enc) )
[ "def", "_refine_enc", "(", "enc", ")", ":", "rsa", "=", "[", "'r'", ",", "'rsa'", ",", "'ssh-rsa'", "]", "dss", "=", "[", "'d'", ",", "'dsa'", ",", "'dss'", ",", "'ssh-dss'", "]", "ecdsa", "=", "[", "'e'", ",", "'ecdsa'", ",", "'ecdsa-sha2-nistp521'"...
Return the properly formatted ssh value for the authorized encryption key type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string if using higher enc. If the type is not found, raise CommandExecutionError.
[ "Return", "the", "properly", "formatted", "ssh", "value", "for", "the", "authorized", "encryption", "key", "type", ".", "ecdsa", "defaults", "to", "256", "bits", "must", "give", "full", "ecdsa", "enc", "schema", "string", "if", "using", "higher", "enc", ".",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L52-L80
train
saltstack/salt
salt/modules/ssh.py
_format_auth_line
def _format_auth_line(key, enc, comment, options): ''' Properly format user input. ''' line = '' if options: line += '{0} '.format(','.join(options)) line += '{0} {1} {2}\n'.format(enc, key, comment) return line
python
def _format_auth_line(key, enc, comment, options): ''' Properly format user input. ''' line = '' if options: line += '{0} '.format(','.join(options)) line += '{0} {1} {2}\n'.format(enc, key, comment) return line
[ "def", "_format_auth_line", "(", "key", ",", "enc", ",", "comment", ",", "options", ")", ":", "line", "=", "''", "if", "options", ":", "line", "+=", "'{0} '", ".", "format", "(", "','", ".", "join", "(", "options", ")", ")", "line", "+=", "'{0} {1} {...
Properly format user input.
[ "Properly", "format", "user", "input", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L83-L91
train
saltstack/salt
salt/modules/ssh.py
_expand_authorized_keys_path
def _expand_authorized_keys_path(path, user, home): ''' Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5) ''' converted_path = '' had_escape = False for char in path: if had_escape: had_escape = False if char == '%': converted_path += '%' elif char == 'u': converted_path += user elif char == 'h': converted_path += home else: error = 'AuthorizedKeysFile path: unknown token character "%{0}"'.format(char) raise CommandExecutionError(error) continue elif char == '%': had_escape = True else: converted_path += char if had_escape: error = "AuthorizedKeysFile path: Last character can't be escape character" raise CommandExecutionError(error) return converted_path
python
def _expand_authorized_keys_path(path, user, home): ''' Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5) ''' converted_path = '' had_escape = False for char in path: if had_escape: had_escape = False if char == '%': converted_path += '%' elif char == 'u': converted_path += user elif char == 'h': converted_path += home else: error = 'AuthorizedKeysFile path: unknown token character "%{0}"'.format(char) raise CommandExecutionError(error) continue elif char == '%': had_escape = True else: converted_path += char if had_escape: error = "AuthorizedKeysFile path: Last character can't be escape character" raise CommandExecutionError(error) return converted_path
[ "def", "_expand_authorized_keys_path", "(", "path", ",", "user", ",", "home", ")", ":", "converted_path", "=", "''", "had_escape", "=", "False", "for", "char", "in", "path", ":", "if", "had_escape", ":", "had_escape", "=", "False", "if", "char", "==", "'%'...
Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5)
[ "Expand", "the", "AuthorizedKeysFile", "expression", ".", "Defined", "in", "man", "sshd_config", "(", "5", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L94-L120
train
saltstack/salt
salt/modules/ssh.py
_get_config_file
def _get_config_file(user, config): ''' Get absolute path to a user's ssh_config. ''' uinfo = __salt__['user.info'](user) if not uinfo: raise CommandExecutionError('User \'{0}\' does not exist'.format(user)) home = uinfo['home'] config = _expand_authorized_keys_path(config, user, home) if not os.path.isabs(config): config = os.path.join(home, config) return config
python
def _get_config_file(user, config): ''' Get absolute path to a user's ssh_config. ''' uinfo = __salt__['user.info'](user) if not uinfo: raise CommandExecutionError('User \'{0}\' does not exist'.format(user)) home = uinfo['home'] config = _expand_authorized_keys_path(config, user, home) if not os.path.isabs(config): config = os.path.join(home, config) return config
[ "def", "_get_config_file", "(", "user", ",", "config", ")", ":", "uinfo", "=", "__salt__", "[", "'user.info'", "]", "(", "user", ")", "if", "not", "uinfo", ":", "raise", "CommandExecutionError", "(", "'User \\'{0}\\' does not exist'", ".", "format", "(", "user...
Get absolute path to a user's ssh_config.
[ "Get", "absolute", "path", "to", "a", "user", "s", "ssh_config", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L123-L134
train
saltstack/salt
salt/modules/ssh.py
_replace_auth_key
def _replace_auth_key( user, key, enc='ssh-rsa', comment='', options=None, config='.ssh/authorized_keys'): ''' Replace an existing key ''' auth_line = _format_auth_line(key, enc, comment, options or []) lines = [] full = _get_config_file(user, config) try: # open the file for both reading AND writing with salt.utils.files.fopen(full, 'r') as _fh: for line in _fh: # We don't need any whitespace-only containing lines or arbitrary doubled newlines line = salt.utils.stringutils.to_unicode(line.strip()) if line == '': continue line += '\n' if line.startswith('#'): # Commented Line lines.append(line) continue comps = re.findall(r'((.*)\s)?(ssh-[a-z0-9-]+|ecdsa-[a-z0-9-]+)\s([a-zA-Z0-9+/]+={0,2})(\s(.*))?', line) if comps and len(comps[0]) > 3 and comps[0][3] == key: # Found our key, replace it lines.append(auth_line) else: lines.append(line) _fh.close() # Re-open the file writable after properly closing it with salt.utils.files.fopen(full, 'wb') as _fh: # Write out any changes _fh.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: raise CommandExecutionError( 'Problem reading or writing to key file: {0}'.format(exc) )
python
def _replace_auth_key( user, key, enc='ssh-rsa', comment='', options=None, config='.ssh/authorized_keys'): ''' Replace an existing key ''' auth_line = _format_auth_line(key, enc, comment, options or []) lines = [] full = _get_config_file(user, config) try: # open the file for both reading AND writing with salt.utils.files.fopen(full, 'r') as _fh: for line in _fh: # We don't need any whitespace-only containing lines or arbitrary doubled newlines line = salt.utils.stringutils.to_unicode(line.strip()) if line == '': continue line += '\n' if line.startswith('#'): # Commented Line lines.append(line) continue comps = re.findall(r'((.*)\s)?(ssh-[a-z0-9-]+|ecdsa-[a-z0-9-]+)\s([a-zA-Z0-9+/]+={0,2})(\s(.*))?', line) if comps and len(comps[0]) > 3 and comps[0][3] == key: # Found our key, replace it lines.append(auth_line) else: lines.append(line) _fh.close() # Re-open the file writable after properly closing it with salt.utils.files.fopen(full, 'wb') as _fh: # Write out any changes _fh.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: raise CommandExecutionError( 'Problem reading or writing to key file: {0}'.format(exc) )
[ "def", "_replace_auth_key", "(", "user", ",", "key", ",", "enc", "=", "'ssh-rsa'", ",", "comment", "=", "''", ",", "options", "=", "None", ",", "config", "=", "'.ssh/authorized_keys'", ")", ":", "auth_line", "=", "_format_auth_line", "(", "key", ",", "enc"...
Replace an existing key
[ "Replace", "an", "existing", "key" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L137-L181
train
saltstack/salt
salt/modules/ssh.py
_validate_keys
def _validate_keys(key_file, fingerprint_hash_type): ''' Return a dict containing validated keys in the passed file ''' ret = {} linere = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$') try: with salt.utils.files.fopen(key_file, 'r') as _fh: for line in _fh: # We don't need any whitespace-only containing lines or arbitrary doubled newlines line = salt.utils.stringutils.to_unicode(line.strip()) if line == '': continue line += '\n' if line.startswith('#'): # Commented Line continue # get "{options} key" search = re.search(linere, line) if not search: # not an auth ssh key, perhaps a blank line continue opts = search.group(1) comps = search.group(2).split() if len(comps) < 2: # Not a valid line continue if opts: # It has options, grab them options = opts.split(',') else: options = [] enc = comps[0] key = comps[1] comment = ' '.join(comps[2:]) fingerprint = _fingerprint(key, fingerprint_hash_type) if fingerprint is None: continue ret[key] = {'enc': enc, 'comment': comment, 'options': options, 'fingerprint': fingerprint} except (IOError, OSError): raise CommandExecutionError( 'Problem reading ssh key file {0}'.format(key_file) ) return ret
python
def _validate_keys(key_file, fingerprint_hash_type): ''' Return a dict containing validated keys in the passed file ''' ret = {} linere = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$') try: with salt.utils.files.fopen(key_file, 'r') as _fh: for line in _fh: # We don't need any whitespace-only containing lines or arbitrary doubled newlines line = salt.utils.stringutils.to_unicode(line.strip()) if line == '': continue line += '\n' if line.startswith('#'): # Commented Line continue # get "{options} key" search = re.search(linere, line) if not search: # not an auth ssh key, perhaps a blank line continue opts = search.group(1) comps = search.group(2).split() if len(comps) < 2: # Not a valid line continue if opts: # It has options, grab them options = opts.split(',') else: options = [] enc = comps[0] key = comps[1] comment = ' '.join(comps[2:]) fingerprint = _fingerprint(key, fingerprint_hash_type) if fingerprint is None: continue ret[key] = {'enc': enc, 'comment': comment, 'options': options, 'fingerprint': fingerprint} except (IOError, OSError): raise CommandExecutionError( 'Problem reading ssh key file {0}'.format(key_file) ) return ret
[ "def", "_validate_keys", "(", "key_file", ",", "fingerprint_hash_type", ")", ":", "ret", "=", "{", "}", "linere", "=", "re", ".", "compile", "(", "r'^(.*?)\\s?((?:ssh\\-|ecds)[\\w-]+\\s.+)$'", ")", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", ...
Return a dict containing validated keys in the passed file
[ "Return", "a", "dict", "containing", "validated", "keys", "in", "the", "passed", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L184-L239
train
saltstack/salt
salt/modules/ssh.py
_fingerprint
def _fingerprint(public_key, fingerprint_hash_type): ''' Return a public key fingerprint based on its base64-encoded representation The fingerprint string is formatted according to RFC 4716 (ch.4), that is, in the form "xx:xx:...:xx" If the key is invalid (incorrect base64 string), return None public_key The public key to return the fingerprint for fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` ''' if fingerprint_hash_type: hash_type = fingerprint_hash_type.lower() else: hash_type = 'sha256' try: hash_func = getattr(hashlib, hash_type) except AttributeError: raise CommandExecutionError( 'The fingerprint_hash_type {0} is not supported.'.format( hash_type ) ) try: if six.PY2: raw_key = public_key.decode('base64') else: raw_key = base64.b64decode(public_key, validate=True) # pylint: disable=E1123 except binascii.Error: return None ret = hash_func(raw_key).hexdigest() chunks = [ret[i:i + 2] for i in range(0, len(ret), 2)] return ':'.join(chunks)
python
def _fingerprint(public_key, fingerprint_hash_type): ''' Return a public key fingerprint based on its base64-encoded representation The fingerprint string is formatted according to RFC 4716 (ch.4), that is, in the form "xx:xx:...:xx" If the key is invalid (incorrect base64 string), return None public_key The public key to return the fingerprint for fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` ''' if fingerprint_hash_type: hash_type = fingerprint_hash_type.lower() else: hash_type = 'sha256' try: hash_func = getattr(hashlib, hash_type) except AttributeError: raise CommandExecutionError( 'The fingerprint_hash_type {0} is not supported.'.format( hash_type ) ) try: if six.PY2: raw_key = public_key.decode('base64') else: raw_key = base64.b64decode(public_key, validate=True) # pylint: disable=E1123 except binascii.Error: return None ret = hash_func(raw_key).hexdigest() chunks = [ret[i:i + 2] for i in range(0, len(ret), 2)] return ':'.join(chunks)
[ "def", "_fingerprint", "(", "public_key", ",", "fingerprint_hash_type", ")", ":", "if", "fingerprint_hash_type", ":", "hash_type", "=", "fingerprint_hash_type", ".", "lower", "(", ")", "else", ":", "hash_type", "=", "'sha256'", "try", ":", "hash_func", "=", "get...
Return a public key fingerprint based on its base64-encoded representation The fingerprint string is formatted according to RFC 4716 (ch.4), that is, in the form "xx:xx:...:xx" If the key is invalid (incorrect base64 string), return None public_key The public key to return the fingerprint for fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256``
[ "Return", "a", "public", "key", "fingerprint", "based", "on", "its", "base64", "-", "encoded", "representation" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L242-L287
train
saltstack/salt
salt/modules/ssh.py
host_keys
def host_keys(keydir=None, private=True, certs=True): ''' Return the minion's host keys CLI Example: .. code-block:: bash salt '*' ssh.host_keys salt '*' ssh.host_keys keydir=/etc/ssh salt '*' ssh.host_keys keydir=/etc/ssh private=False salt '*' ssh.host_keys keydir=/etc/ssh certs=False ''' # TODO: support parsing sshd_config for the key directory if not keydir: if __grains__['kernel'] == 'Linux': keydir = '/etc/ssh' else: # If keydir is None, os.listdir() will blow up raise SaltInvocationError('ssh.host_keys: Please specify a keydir') keys = {} fnre = re.compile( r'ssh_host_(?P<type>.+)_key(?P<pub>(?P<cert>-cert)?\.pub)?') for fn_ in os.listdir(keydir): m = fnre.match(fn_) if m: if not m.group('pub') and private is False: log.info('Skipping private key file %s as ' 'private is set to False', fn_) continue if m.group('cert') and certs is False: log.info( 'Skipping key file %s as certs is set to False', fn_ ) continue kname = m.group('type') if m.group('pub'): kname += m.group('pub') try: with salt.utils.files.fopen(os.path.join(keydir, fn_), 'r') as _fh: # As of RFC 4716 "a key file is a text file, containing a # sequence of lines", although some SSH implementations # (e.g. OpenSSH) manage their own format(s). Please see # #20708 for a discussion about how to handle SSH key files # in the future keys[kname] = salt.utils.stringutils.to_unicode(_fh.readline()) # only read the whole file if it is not in the legacy 1.1 # binary format if keys[kname] != "SSH PRIVATE KEY FILE FORMAT 1.1\n": keys[kname] += salt.utils.stringutils.to_unicode(_fh.read()) keys[kname] = keys[kname].strip() except (IOError, OSError): keys[kname] = '' return keys
python
def host_keys(keydir=None, private=True, certs=True): ''' Return the minion's host keys CLI Example: .. code-block:: bash salt '*' ssh.host_keys salt '*' ssh.host_keys keydir=/etc/ssh salt '*' ssh.host_keys keydir=/etc/ssh private=False salt '*' ssh.host_keys keydir=/etc/ssh certs=False ''' # TODO: support parsing sshd_config for the key directory if not keydir: if __grains__['kernel'] == 'Linux': keydir = '/etc/ssh' else: # If keydir is None, os.listdir() will blow up raise SaltInvocationError('ssh.host_keys: Please specify a keydir') keys = {} fnre = re.compile( r'ssh_host_(?P<type>.+)_key(?P<pub>(?P<cert>-cert)?\.pub)?') for fn_ in os.listdir(keydir): m = fnre.match(fn_) if m: if not m.group('pub') and private is False: log.info('Skipping private key file %s as ' 'private is set to False', fn_) continue if m.group('cert') and certs is False: log.info( 'Skipping key file %s as certs is set to False', fn_ ) continue kname = m.group('type') if m.group('pub'): kname += m.group('pub') try: with salt.utils.files.fopen(os.path.join(keydir, fn_), 'r') as _fh: # As of RFC 4716 "a key file is a text file, containing a # sequence of lines", although some SSH implementations # (e.g. OpenSSH) manage their own format(s). Please see # #20708 for a discussion about how to handle SSH key files # in the future keys[kname] = salt.utils.stringutils.to_unicode(_fh.readline()) # only read the whole file if it is not in the legacy 1.1 # binary format if keys[kname] != "SSH PRIVATE KEY FILE FORMAT 1.1\n": keys[kname] += salt.utils.stringutils.to_unicode(_fh.read()) keys[kname] = keys[kname].strip() except (IOError, OSError): keys[kname] = '' return keys
[ "def", "host_keys", "(", "keydir", "=", "None", ",", "private", "=", "True", ",", "certs", "=", "True", ")", ":", "# TODO: support parsing sshd_config for the key directory", "if", "not", "keydir", ":", "if", "__grains__", "[", "'kernel'", "]", "==", "'Linux'", ...
Return the minion's host keys CLI Example: .. code-block:: bash salt '*' ssh.host_keys salt '*' ssh.host_keys keydir=/etc/ssh salt '*' ssh.host_keys keydir=/etc/ssh private=False salt '*' ssh.host_keys keydir=/etc/ssh certs=False
[ "Return", "the", "minion", "s", "host", "keys" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L314-L370
train
saltstack/salt
salt/modules/ssh.py
auth_keys
def auth_keys(user=None, config='.ssh/authorized_keys', fingerprint_hash_type=None): ''' Return the authorized keys for users CLI Example: .. code-block:: bash salt '*' ssh.auth_keys salt '*' ssh.auth_keys root salt '*' ssh.auth_keys user=root salt '*' ssh.auth_keys user="[user1, user2]" ''' if not user: user = __salt__['user.list_users']() old_output_when_one_user = False if not isinstance(user, list): user = [user] old_output_when_one_user = True keys = {} for u in user: full = None try: full = _get_config_file(u, config) except CommandExecutionError: pass if full and os.path.isfile(full): keys[u] = _validate_keys(full, fingerprint_hash_type) if old_output_when_one_user: if user[0] in keys: return keys[user[0]] else: return {} return keys
python
def auth_keys(user=None, config='.ssh/authorized_keys', fingerprint_hash_type=None): ''' Return the authorized keys for users CLI Example: .. code-block:: bash salt '*' ssh.auth_keys salt '*' ssh.auth_keys root salt '*' ssh.auth_keys user=root salt '*' ssh.auth_keys user="[user1, user2]" ''' if not user: user = __salt__['user.list_users']() old_output_when_one_user = False if not isinstance(user, list): user = [user] old_output_when_one_user = True keys = {} for u in user: full = None try: full = _get_config_file(u, config) except CommandExecutionError: pass if full and os.path.isfile(full): keys[u] = _validate_keys(full, fingerprint_hash_type) if old_output_when_one_user: if user[0] in keys: return keys[user[0]] else: return {} return keys
[ "def", "auth_keys", "(", "user", "=", "None", ",", "config", "=", "'.ssh/authorized_keys'", ",", "fingerprint_hash_type", "=", "None", ")", ":", "if", "not", "user", ":", "user", "=", "__salt__", "[", "'user.list_users'", "]", "(", ")", "old_output_when_one_us...
Return the authorized keys for users CLI Example: .. code-block:: bash salt '*' ssh.auth_keys salt '*' ssh.auth_keys root salt '*' ssh.auth_keys user=root salt '*' ssh.auth_keys user="[user1, user2]"
[ "Return", "the", "authorized", "keys", "for", "users" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L373-L413
train
saltstack/salt
salt/modules/ssh.py
check_key_file
def check_key_file(user, source, config='.ssh/authorized_keys', saltenv='base', fingerprint_hash_type=None): ''' Check a keyfile from a source destination against the local keys and return the keys to change CLI Example: .. code-block:: bash salt '*' ssh.check_key_file root salt://ssh/keyfile ''' keyfile = __salt__['cp.cache_file'](source, saltenv) if not keyfile: return {} s_keys = _validate_keys(keyfile, fingerprint_hash_type) if not s_keys: err = 'No keys detected in {0}. Is file properly ' \ 'formatted?'.format(source) log.error(err) __context__['ssh_auth.error'] = err return {} else: ret = {} for key in s_keys: ret[key] = check_key( user, key, s_keys[key]['enc'], s_keys[key]['comment'], s_keys[key]['options'], config=config, fingerprint_hash_type=fingerprint_hash_type) return ret
python
def check_key_file(user, source, config='.ssh/authorized_keys', saltenv='base', fingerprint_hash_type=None): ''' Check a keyfile from a source destination against the local keys and return the keys to change CLI Example: .. code-block:: bash salt '*' ssh.check_key_file root salt://ssh/keyfile ''' keyfile = __salt__['cp.cache_file'](source, saltenv) if not keyfile: return {} s_keys = _validate_keys(keyfile, fingerprint_hash_type) if not s_keys: err = 'No keys detected in {0}. Is file properly ' \ 'formatted?'.format(source) log.error(err) __context__['ssh_auth.error'] = err return {} else: ret = {} for key in s_keys: ret[key] = check_key( user, key, s_keys[key]['enc'], s_keys[key]['comment'], s_keys[key]['options'], config=config, fingerprint_hash_type=fingerprint_hash_type) return ret
[ "def", "check_key_file", "(", "user", ",", "source", ",", "config", "=", "'.ssh/authorized_keys'", ",", "saltenv", "=", "'base'", ",", "fingerprint_hash_type", "=", "None", ")", ":", "keyfile", "=", "__salt__", "[", "'cp.cache_file'", "]", "(", "source", ",", ...
Check a keyfile from a source destination against the local keys and return the keys to change CLI Example: .. code-block:: bash salt '*' ssh.check_key_file root salt://ssh/keyfile
[ "Check", "a", "keyfile", "from", "a", "source", "destination", "against", "the", "local", "keys", "and", "return", "the", "keys", "to", "change" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L416-L452
train
saltstack/salt
salt/modules/ssh.py
check_key
def check_key(user, key, enc, comment, options, config='.ssh/authorized_keys', cache_keys=None, fingerprint_hash_type=None): ''' Check to see if a key needs updating, returns "update", "add" or "exists" CLI Example: .. code-block:: bash salt '*' ssh.check_key <user> <key> <enc> <comment> <options> ''' if cache_keys is None: cache_keys = [] enc = _refine_enc(enc) current = auth_keys(user, config=config, fingerprint_hash_type=fingerprint_hash_type) nline = _format_auth_line(key, enc, comment, options) # Removing existing keys from the auth_keys isn't really a good idea # in fact # # as: # - We can have non-salt managed keys in that file # - We can have multiple states defining keys for an user # and with such code only one state will win # the remove all-other-keys war # # if cache_keys: # for pub_key in set(current).difference(set(cache_keys)): # rm_auth_key(user, pub_key) if key in current: cline = _format_auth_line(key, current[key]['enc'], current[key]['comment'], current[key]['options']) if cline != nline: return 'update' else: return 'add' return 'exists'
python
def check_key(user, key, enc, comment, options, config='.ssh/authorized_keys', cache_keys=None, fingerprint_hash_type=None): ''' Check to see if a key needs updating, returns "update", "add" or "exists" CLI Example: .. code-block:: bash salt '*' ssh.check_key <user> <key> <enc> <comment> <options> ''' if cache_keys is None: cache_keys = [] enc = _refine_enc(enc) current = auth_keys(user, config=config, fingerprint_hash_type=fingerprint_hash_type) nline = _format_auth_line(key, enc, comment, options) # Removing existing keys from the auth_keys isn't really a good idea # in fact # # as: # - We can have non-salt managed keys in that file # - We can have multiple states defining keys for an user # and with such code only one state will win # the remove all-other-keys war # # if cache_keys: # for pub_key in set(current).difference(set(cache_keys)): # rm_auth_key(user, pub_key) if key in current: cline = _format_auth_line(key, current[key]['enc'], current[key]['comment'], current[key]['options']) if cline != nline: return 'update' else: return 'add' return 'exists'
[ "def", "check_key", "(", "user", ",", "key", ",", "enc", ",", "comment", ",", "options", ",", "config", "=", "'.ssh/authorized_keys'", ",", "cache_keys", "=", "None", ",", "fingerprint_hash_type", "=", "None", ")", ":", "if", "cache_keys", "is", "None", ":...
Check to see if a key needs updating, returns "update", "add" or "exists" CLI Example: .. code-block:: bash salt '*' ssh.check_key <user> <key> <enc> <comment> <options>
[ "Check", "to", "see", "if", "a", "key", "needs", "updating", "returns", "update", "add", "or", "exists" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L455-L502
train
saltstack/salt
salt/modules/ssh.py
rm_auth_key_from_file
def rm_auth_key_from_file(user, source, config='.ssh/authorized_keys', saltenv='base', fingerprint_hash_type=None): ''' Remove an authorized key from the specified user's authorized key file, using a file as source CLI Example: .. code-block:: bash salt '*' ssh.rm_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub ''' lfile = __salt__['cp.cache_file'](source, saltenv) if not os.path.isfile(lfile): raise CommandExecutionError( 'Failed to pull key file from salt file server' ) s_keys = _validate_keys(lfile, fingerprint_hash_type) if not s_keys: err = ( 'No keys detected in {0}. Is file properly formatted?'.format( source ) ) log.error(err) __context__['ssh_auth.error'] = err return 'fail' else: rval = '' for key in s_keys: rval += rm_auth_key( user, key, config=config, fingerprint_hash_type=fingerprint_hash_type ) # Due to the ability for a single file to have multiple keys, it's # possible for a single call to this function to have both "replace" # and "new" as possible valid returns. I ordered the following as I # thought best. if 'Key not removed' in rval: return 'Key not removed' elif 'Key removed' in rval: return 'Key removed' else: return 'Key not present'
python
def rm_auth_key_from_file(user, source, config='.ssh/authorized_keys', saltenv='base', fingerprint_hash_type=None): ''' Remove an authorized key from the specified user's authorized key file, using a file as source CLI Example: .. code-block:: bash salt '*' ssh.rm_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub ''' lfile = __salt__['cp.cache_file'](source, saltenv) if not os.path.isfile(lfile): raise CommandExecutionError( 'Failed to pull key file from salt file server' ) s_keys = _validate_keys(lfile, fingerprint_hash_type) if not s_keys: err = ( 'No keys detected in {0}. Is file properly formatted?'.format( source ) ) log.error(err) __context__['ssh_auth.error'] = err return 'fail' else: rval = '' for key in s_keys: rval += rm_auth_key( user, key, config=config, fingerprint_hash_type=fingerprint_hash_type ) # Due to the ability for a single file to have multiple keys, it's # possible for a single call to this function to have both "replace" # and "new" as possible valid returns. I ordered the following as I # thought best. if 'Key not removed' in rval: return 'Key not removed' elif 'Key removed' in rval: return 'Key removed' else: return 'Key not present'
[ "def", "rm_auth_key_from_file", "(", "user", ",", "source", ",", "config", "=", "'.ssh/authorized_keys'", ",", "saltenv", "=", "'base'", ",", "fingerprint_hash_type", "=", "None", ")", ":", "lfile", "=", "__salt__", "[", "'cp.cache_file'", "]", "(", "source", ...
Remove an authorized key from the specified user's authorized key file, using a file as source CLI Example: .. code-block:: bash salt '*' ssh.rm_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub
[ "Remove", "an", "authorized", "key", "from", "the", "specified", "user", "s", "authorized", "key", "file", "using", "a", "file", "as", "source" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L505-L554
train
saltstack/salt
salt/modules/ssh.py
rm_auth_key
def rm_auth_key(user, key, config='.ssh/authorized_keys', fingerprint_hash_type=None): ''' Remove an authorized key from the specified user's authorized key file CLI Example: .. code-block:: bash salt '*' ssh.rm_auth_key <user> <key> ''' current = auth_keys(user, config=config, fingerprint_hash_type=fingerprint_hash_type) linere = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$') if key in current: # Remove the key full = _get_config_file(user, config) # Return something sensible if the file doesn't exist if not os.path.isfile(full): return 'Authorized keys file {0} not present'.format(full) lines = [] try: # Read every line in the file to find the right ssh key # and then write out the correct one. Open the file once with salt.utils.files.fopen(full, 'r') as _fh: for line in _fh: # We don't need any whitespace-only containing lines or arbitrary doubled newlines line = salt.utils.stringutils.to_unicode(line.strip()) if line == '': continue line += '\n' if line.startswith('#'): # Commented Line lines.append(line) continue # get "{options} key" search = re.search(linere, line) if not search: # not an auth ssh key, perhaps a blank line continue comps = search.group(2).split() if len(comps) < 2: # Not a valid line lines.append(line) continue pkey = comps[1] # This is the key we are "deleting", so don't put # it in the list of keys to be re-added back if pkey == key: continue lines.append(line) # Let the context manager do the right thing here and then # re-open the file in write mode to save the changes out. with salt.utils.files.fopen(full, 'wb') as _fh: _fh.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: log.warning('Could not read/write key file: %s', exc) return 'Key not removed' return 'Key removed' # TODO: Should this function return a simple boolean? return 'Key not present'
python
def rm_auth_key(user, key, config='.ssh/authorized_keys', fingerprint_hash_type=None): ''' Remove an authorized key from the specified user's authorized key file CLI Example: .. code-block:: bash salt '*' ssh.rm_auth_key <user> <key> ''' current = auth_keys(user, config=config, fingerprint_hash_type=fingerprint_hash_type) linere = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$') if key in current: # Remove the key full = _get_config_file(user, config) # Return something sensible if the file doesn't exist if not os.path.isfile(full): return 'Authorized keys file {0} not present'.format(full) lines = [] try: # Read every line in the file to find the right ssh key # and then write out the correct one. Open the file once with salt.utils.files.fopen(full, 'r') as _fh: for line in _fh: # We don't need any whitespace-only containing lines or arbitrary doubled newlines line = salt.utils.stringutils.to_unicode(line.strip()) if line == '': continue line += '\n' if line.startswith('#'): # Commented Line lines.append(line) continue # get "{options} key" search = re.search(linere, line) if not search: # not an auth ssh key, perhaps a blank line continue comps = search.group(2).split() if len(comps) < 2: # Not a valid line lines.append(line) continue pkey = comps[1] # This is the key we are "deleting", so don't put # it in the list of keys to be re-added back if pkey == key: continue lines.append(line) # Let the context manager do the right thing here and then # re-open the file in write mode to save the changes out. with salt.utils.files.fopen(full, 'wb') as _fh: _fh.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: log.warning('Could not read/write key file: %s', exc) return 'Key not removed' return 'Key removed' # TODO: Should this function return a simple boolean? return 'Key not present'
[ "def", "rm_auth_key", "(", "user", ",", "key", ",", "config", "=", "'.ssh/authorized_keys'", ",", "fingerprint_hash_type", "=", "None", ")", ":", "current", "=", "auth_keys", "(", "user", ",", "config", "=", "config", ",", "fingerprint_hash_type", "=", "finger...
Remove an authorized key from the specified user's authorized key file CLI Example: .. code-block:: bash salt '*' ssh.rm_auth_key <user> <key>
[ "Remove", "an", "authorized", "key", "from", "the", "specified", "user", "s", "authorized", "key", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L557-L631
train
saltstack/salt
salt/modules/ssh.py
set_auth_key_from_file
def set_auth_key_from_file(user, source, config='.ssh/authorized_keys', saltenv='base', fingerprint_hash_type=None): ''' Add a key to the authorized_keys file, using a file as the source. CLI Example: .. code-block:: bash salt '*' ssh.set_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub ''' # TODO: add support for pulling keys from other file sources as well lfile = __salt__['cp.cache_file'](source, saltenv) if not os.path.isfile(lfile): raise CommandExecutionError( 'Failed to pull key file from salt file server' ) s_keys = _validate_keys(lfile, fingerprint_hash_type) if not s_keys: err = ( 'No keys detected in {0}. Is file properly formatted?'.format( source ) ) log.error(err) __context__['ssh_auth.error'] = err return 'fail' else: rval = '' for key in s_keys: rval += set_auth_key( user, key, enc=s_keys[key]['enc'], comment=s_keys[key]['comment'], options=s_keys[key]['options'], config=config, cache_keys=list(s_keys.keys()), fingerprint_hash_type=fingerprint_hash_type ) # Due to the ability for a single file to have multiple keys, it's # possible for a single call to this function to have both "replace" # and "new" as possible valid returns. I ordered the following as I # thought best. if 'fail' in rval: return 'fail' elif 'replace' in rval: return 'replace' elif 'new' in rval: return 'new' else: return 'no change'
python
def set_auth_key_from_file(user, source, config='.ssh/authorized_keys', saltenv='base', fingerprint_hash_type=None): ''' Add a key to the authorized_keys file, using a file as the source. CLI Example: .. code-block:: bash salt '*' ssh.set_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub ''' # TODO: add support for pulling keys from other file sources as well lfile = __salt__['cp.cache_file'](source, saltenv) if not os.path.isfile(lfile): raise CommandExecutionError( 'Failed to pull key file from salt file server' ) s_keys = _validate_keys(lfile, fingerprint_hash_type) if not s_keys: err = ( 'No keys detected in {0}. Is file properly formatted?'.format( source ) ) log.error(err) __context__['ssh_auth.error'] = err return 'fail' else: rval = '' for key in s_keys: rval += set_auth_key( user, key, enc=s_keys[key]['enc'], comment=s_keys[key]['comment'], options=s_keys[key]['options'], config=config, cache_keys=list(s_keys.keys()), fingerprint_hash_type=fingerprint_hash_type ) # Due to the ability for a single file to have multiple keys, it's # possible for a single call to this function to have both "replace" # and "new" as possible valid returns. I ordered the following as I # thought best. if 'fail' in rval: return 'fail' elif 'replace' in rval: return 'replace' elif 'new' in rval: return 'new' else: return 'no change'
[ "def", "set_auth_key_from_file", "(", "user", ",", "source", ",", "config", "=", "'.ssh/authorized_keys'", ",", "saltenv", "=", "'base'", ",", "fingerprint_hash_type", "=", "None", ")", ":", "# TODO: add support for pulling keys from other file sources as well", "lfile", ...
Add a key to the authorized_keys file, using a file as the source. CLI Example: .. code-block:: bash salt '*' ssh.set_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub
[ "Add", "a", "key", "to", "the", "authorized_keys", "file", "using", "a", "file", "as", "the", "source", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L634-L689
train
saltstack/salt
salt/modules/ssh.py
set_auth_key
def set_auth_key( user, key, enc='ssh-rsa', comment='', options=None, config='.ssh/authorized_keys', cache_keys=None, fingerprint_hash_type=None): ''' Add a key to the authorized_keys file. The "key" parameter must only be the string of text that is the encoded key. If the key begins with "ssh-rsa" or ends with user@host, remove those from the key before passing it to this function. CLI Example: .. code-block:: bash salt '*' ssh.set_auth_key <user> '<key>' enc='dsa' ''' if cache_keys is None: cache_keys = [] if len(key.split()) > 1: return 'invalid' enc = _refine_enc(enc) uinfo = __salt__['user.info'](user) if not uinfo: return 'fail' # A 'valid key' to us pretty much means 'decodable as base64', which is # the same filtering done when reading the authorized_keys file. Apply # the same check to ensure we don't insert anything that will not # subsequently be read) key_is_valid = _fingerprint(key, fingerprint_hash_type) is not None if not key_is_valid: return 'Invalid public key' status = check_key(user, key, enc, comment, options, config=config, cache_keys=cache_keys, fingerprint_hash_type=fingerprint_hash_type) if status == 'update': _replace_auth_key(user, key, enc, comment, options or [], config) return 'replace' elif status == 'exists': return 'no change' else: auth_line = _format_auth_line(key, enc, comment, options) fconfig = _get_config_file(user, config) # Fail if the key lives under the user's homedir, and the homedir # doesn't exist udir = uinfo.get('home', '') if fconfig.startswith(udir) and not os.path.isdir(udir): return 'fail' if not os.path.isdir(os.path.dirname(fconfig)): dpath = os.path.dirname(fconfig) os.makedirs(dpath) if not salt.utils.platform.is_windows(): if os.geteuid() == 0: os.chown(dpath, uinfo['uid'], uinfo['gid']) os.chmod(dpath, 448) # If SELINUX is available run a restorecon on the file rcon = salt.utils.path.which('restorecon') if rcon: cmd = [rcon, dpath] subprocess.call(cmd) if not os.path.isfile(fconfig): new_file = True else: new_file = False try: with salt.utils.files.fopen(fconfig, 'ab+') as _fh: if new_file is False: # Let's make sure we have a new line at the end of the file _fh.seek(0, 2) if _fh.tell() > 0: # File isn't empty, check if last byte is a newline # If not, add one _fh.seek(-1, 2) if _fh.read(1) != b'\n': _fh.write(b'\n') _fh.write(salt.utils.stringutils.to_bytes(auth_line)) except (IOError, OSError) as exc: msg = 'Could not write to key file: {0}' raise CommandExecutionError(msg.format(exc)) if new_file: if not salt.utils.platform.is_windows(): if os.geteuid() == 0: os.chown(fconfig, uinfo['uid'], uinfo['gid']) os.chmod(fconfig, 384) # If SELINUX is available run a restorecon on the file rcon = salt.utils.path.which('restorecon') if rcon: cmd = [rcon, fconfig] subprocess.call(cmd) return 'new'
python
def set_auth_key( user, key, enc='ssh-rsa', comment='', options=None, config='.ssh/authorized_keys', cache_keys=None, fingerprint_hash_type=None): ''' Add a key to the authorized_keys file. The "key" parameter must only be the string of text that is the encoded key. If the key begins with "ssh-rsa" or ends with user@host, remove those from the key before passing it to this function. CLI Example: .. code-block:: bash salt '*' ssh.set_auth_key <user> '<key>' enc='dsa' ''' if cache_keys is None: cache_keys = [] if len(key.split()) > 1: return 'invalid' enc = _refine_enc(enc) uinfo = __salt__['user.info'](user) if not uinfo: return 'fail' # A 'valid key' to us pretty much means 'decodable as base64', which is # the same filtering done when reading the authorized_keys file. Apply # the same check to ensure we don't insert anything that will not # subsequently be read) key_is_valid = _fingerprint(key, fingerprint_hash_type) is not None if not key_is_valid: return 'Invalid public key' status = check_key(user, key, enc, comment, options, config=config, cache_keys=cache_keys, fingerprint_hash_type=fingerprint_hash_type) if status == 'update': _replace_auth_key(user, key, enc, comment, options or [], config) return 'replace' elif status == 'exists': return 'no change' else: auth_line = _format_auth_line(key, enc, comment, options) fconfig = _get_config_file(user, config) # Fail if the key lives under the user's homedir, and the homedir # doesn't exist udir = uinfo.get('home', '') if fconfig.startswith(udir) and not os.path.isdir(udir): return 'fail' if not os.path.isdir(os.path.dirname(fconfig)): dpath = os.path.dirname(fconfig) os.makedirs(dpath) if not salt.utils.platform.is_windows(): if os.geteuid() == 0: os.chown(dpath, uinfo['uid'], uinfo['gid']) os.chmod(dpath, 448) # If SELINUX is available run a restorecon on the file rcon = salt.utils.path.which('restorecon') if rcon: cmd = [rcon, dpath] subprocess.call(cmd) if not os.path.isfile(fconfig): new_file = True else: new_file = False try: with salt.utils.files.fopen(fconfig, 'ab+') as _fh: if new_file is False: # Let's make sure we have a new line at the end of the file _fh.seek(0, 2) if _fh.tell() > 0: # File isn't empty, check if last byte is a newline # If not, add one _fh.seek(-1, 2) if _fh.read(1) != b'\n': _fh.write(b'\n') _fh.write(salt.utils.stringutils.to_bytes(auth_line)) except (IOError, OSError) as exc: msg = 'Could not write to key file: {0}' raise CommandExecutionError(msg.format(exc)) if new_file: if not salt.utils.platform.is_windows(): if os.geteuid() == 0: os.chown(fconfig, uinfo['uid'], uinfo['gid']) os.chmod(fconfig, 384) # If SELINUX is available run a restorecon on the file rcon = salt.utils.path.which('restorecon') if rcon: cmd = [rcon, fconfig] subprocess.call(cmd) return 'new'
[ "def", "set_auth_key", "(", "user", ",", "key", ",", "enc", "=", "'ssh-rsa'", ",", "comment", "=", "''", ",", "options", "=", "None", ",", "config", "=", "'.ssh/authorized_keys'", ",", "cache_keys", "=", "None", ",", "fingerprint_hash_type", "=", "None", "...
Add a key to the authorized_keys file. The "key" parameter must only be the string of text that is the encoded key. If the key begins with "ssh-rsa" or ends with user@host, remove those from the key before passing it to this function. CLI Example: .. code-block:: bash salt '*' ssh.set_auth_key <user> '<key>' enc='dsa'
[ "Add", "a", "key", "to", "the", "authorized_keys", "file", ".", "The", "key", "parameter", "must", "only", "be", "the", "string", "of", "text", "that", "is", "the", "encoded", "key", ".", "If", "the", "key", "begins", "with", "ssh", "-", "rsa", "or", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L692-L796
train
saltstack/salt
salt/modules/ssh.py
_get_matched_host_line_numbers
def _get_matched_host_line_numbers(lines, enc): ''' Helper function which parses ssh-keygen -F function output and yield line number of known_hosts entries with encryption key type matching enc, one by one. ''' enc = enc if enc else "rsa" for i, line in enumerate(lines): if i % 2 == 0: line_no = int(line.strip().split()[-1]) line_enc = lines[i + 1].strip().split()[-2] if line_enc != enc: continue yield line_no
python
def _get_matched_host_line_numbers(lines, enc): ''' Helper function which parses ssh-keygen -F function output and yield line number of known_hosts entries with encryption key type matching enc, one by one. ''' enc = enc if enc else "rsa" for i, line in enumerate(lines): if i % 2 == 0: line_no = int(line.strip().split()[-1]) line_enc = lines[i + 1].strip().split()[-2] if line_enc != enc: continue yield line_no
[ "def", "_get_matched_host_line_numbers", "(", "lines", ",", "enc", ")", ":", "enc", "=", "enc", "if", "enc", "else", "\"rsa\"", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "i", "%", "2", "==", "0", ":", "line_no", "=", ...
Helper function which parses ssh-keygen -F function output and yield line number of known_hosts entries with encryption key type matching enc, one by one.
[ "Helper", "function", "which", "parses", "ssh", "-", "keygen", "-", "F", "function", "output", "and", "yield", "line", "number", "of", "known_hosts", "entries", "with", "encryption", "key", "type", "matching", "enc", "one", "by", "one", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L799-L812
train
saltstack/salt
salt/modules/ssh.py
_parse_openssh_output
def _parse_openssh_output(lines, fingerprint_hash_type=None): ''' Helper function which parses ssh-keygen -F and ssh-keyscan function output and yield dict with keys information, one by one. ''' for line in lines: # We don't need any whitespace-only containing lines or arbitrary doubled newlines line = line.strip() if line == '': continue line += '\n' if line.startswith('#'): continue try: hostname, enc, key = line.split() except ValueError: # incorrect format continue fingerprint = _fingerprint(key, fingerprint_hash_type=fingerprint_hash_type) if not fingerprint: continue yield {'hostname': hostname, 'key': key, 'enc': enc, 'fingerprint': fingerprint}
python
def _parse_openssh_output(lines, fingerprint_hash_type=None): ''' Helper function which parses ssh-keygen -F and ssh-keyscan function output and yield dict with keys information, one by one. ''' for line in lines: # We don't need any whitespace-only containing lines or arbitrary doubled newlines line = line.strip() if line == '': continue line += '\n' if line.startswith('#'): continue try: hostname, enc, key = line.split() except ValueError: # incorrect format continue fingerprint = _fingerprint(key, fingerprint_hash_type=fingerprint_hash_type) if not fingerprint: continue yield {'hostname': hostname, 'key': key, 'enc': enc, 'fingerprint': fingerprint}
[ "def", "_parse_openssh_output", "(", "lines", ",", "fingerprint_hash_type", "=", "None", ")", ":", "for", "line", "in", "lines", ":", "# We don't need any whitespace-only containing lines or arbitrary doubled newlines", "line", "=", "line", ".", "strip", "(", ")", "if",...
Helper function which parses ssh-keygen -F and ssh-keyscan function output and yield dict with keys information, one by one.
[ "Helper", "function", "which", "parses", "ssh", "-", "keygen", "-", "F", "and", "ssh", "-", "keyscan", "function", "output", "and", "yield", "dict", "with", "keys", "information", "one", "by", "one", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L815-L838
train
saltstack/salt
salt/modules/ssh.py
get_known_host_entries
def get_known_host_entries(user, hostname, config=None, port=None, fingerprint_hash_type=None): ''' .. versionadded:: 2018.3.0 Return information about known host entries from the configfile, if any. If there are no entries for a matching hostname, return None. CLI Example: .. code-block:: bash salt '*' ssh.get_known_host_entries <user> <hostname> ''' full = _get_known_hosts_file(config=config, user=user) if isinstance(full, dict): return full ssh_hostname = _hostname_and_port_to_ssh_hostname(hostname, port) cmd = ['ssh-keygen', '-F', ssh_hostname, '-f', full] lines = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False).splitlines() known_host_entries = list( _parse_openssh_output(lines, fingerprint_hash_type=fingerprint_hash_type) ) return known_host_entries if known_host_entries else None
python
def get_known_host_entries(user, hostname, config=None, port=None, fingerprint_hash_type=None): ''' .. versionadded:: 2018.3.0 Return information about known host entries from the configfile, if any. If there are no entries for a matching hostname, return None. CLI Example: .. code-block:: bash salt '*' ssh.get_known_host_entries <user> <hostname> ''' full = _get_known_hosts_file(config=config, user=user) if isinstance(full, dict): return full ssh_hostname = _hostname_and_port_to_ssh_hostname(hostname, port) cmd = ['ssh-keygen', '-F', ssh_hostname, '-f', full] lines = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False).splitlines() known_host_entries = list( _parse_openssh_output(lines, fingerprint_hash_type=fingerprint_hash_type) ) return known_host_entries if known_host_entries else None
[ "def", "get_known_host_entries", "(", "user", ",", "hostname", ",", "config", "=", "None", ",", "port", "=", "None", ",", "fingerprint_hash_type", "=", "None", ")", ":", "full", "=", "_get_known_hosts_file", "(", "config", "=", "config", ",", "user", "=", ...
.. versionadded:: 2018.3.0 Return information about known host entries from the configfile, if any. If there are no entries for a matching hostname, return None. CLI Example: .. code-block:: bash salt '*' ssh.get_known_host_entries <user> <hostname>
[ "..", "versionadded", "::", "2018", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L842-L873
train
saltstack/salt
salt/modules/ssh.py
recv_known_host_entries
def recv_known_host_entries(hostname, enc=None, port=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' .. versionadded:: 2018.3.0 Retrieve information about host public keys from remote server hostname The name of the remote host (e.g. "github.com") enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss port Optional parameter, denoting the port of the remote host on which an SSH daemon is running. By default the port 22 is used. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. fingerprint_hash_type The fingerprint hash type that the public key fingerprints were originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` CLI Example: .. code-block:: bash salt '*' ssh.recv_known_host_entries <hostname> enc=<enc> port=<port> ''' # The following list of OSes have an old version of openssh-clients # and thus require the '-t' option for ssh-keyscan need_dash_t = ('CentOS-5',) cmd = ['ssh-keyscan'] if port: cmd.extend(['-p', port]) if enc: cmd.extend(['-t', enc]) if not enc and __grains__.get('osfinger') in need_dash_t: cmd.extend(['-t', 'rsa']) cmd.extend(['-T', six.text_type(timeout)]) cmd.append(hostname) lines = None attempts = 5 while not lines and attempts > 0: attempts = attempts - 1 output = __salt__['cmd.run'](cmd, python_shell=False) # This is a workaround because ssh-keyscan hashing is broken for # non-standard SSH ports on basically every platform. See # https://github.com/saltstack/salt/issues/40152 for more info. if hash_known_hosts: # Use a tempdir, because ssh-keygen creates a backup .old file # and we want to get rid of that. We won't need our temp keys # file, either. tempdir = tempfile.mkdtemp() try: filename = os.path.join(tempdir, 'keys') with salt.utils.files.fopen(filename, mode='w') as f: f.write(output) cmd = ['ssh-keygen', '-H', '-f', filename] __salt__['cmd.run'](cmd, python_shell=False) # ssh-keygen moves the old file, so we have to re-open to # read the hashed entries with salt.utils.files.fopen(filename, mode='r') as f: output = f.read() finally: shutil.rmtree(tempdir, ignore_errors=True) lines = output.splitlines() known_host_entries = list(_parse_openssh_output(lines, fingerprint_hash_type=fingerprint_hash_type)) return known_host_entries if known_host_entries else None
python
def recv_known_host_entries(hostname, enc=None, port=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' .. versionadded:: 2018.3.0 Retrieve information about host public keys from remote server hostname The name of the remote host (e.g. "github.com") enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss port Optional parameter, denoting the port of the remote host on which an SSH daemon is running. By default the port 22 is used. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. fingerprint_hash_type The fingerprint hash type that the public key fingerprints were originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` CLI Example: .. code-block:: bash salt '*' ssh.recv_known_host_entries <hostname> enc=<enc> port=<port> ''' # The following list of OSes have an old version of openssh-clients # and thus require the '-t' option for ssh-keyscan need_dash_t = ('CentOS-5',) cmd = ['ssh-keyscan'] if port: cmd.extend(['-p', port]) if enc: cmd.extend(['-t', enc]) if not enc and __grains__.get('osfinger') in need_dash_t: cmd.extend(['-t', 'rsa']) cmd.extend(['-T', six.text_type(timeout)]) cmd.append(hostname) lines = None attempts = 5 while not lines and attempts > 0: attempts = attempts - 1 output = __salt__['cmd.run'](cmd, python_shell=False) # This is a workaround because ssh-keyscan hashing is broken for # non-standard SSH ports on basically every platform. See # https://github.com/saltstack/salt/issues/40152 for more info. if hash_known_hosts: # Use a tempdir, because ssh-keygen creates a backup .old file # and we want to get rid of that. We won't need our temp keys # file, either. tempdir = tempfile.mkdtemp() try: filename = os.path.join(tempdir, 'keys') with salt.utils.files.fopen(filename, mode='w') as f: f.write(output) cmd = ['ssh-keygen', '-H', '-f', filename] __salt__['cmd.run'](cmd, python_shell=False) # ssh-keygen moves the old file, so we have to re-open to # read the hashed entries with salt.utils.files.fopen(filename, mode='r') as f: output = f.read() finally: shutil.rmtree(tempdir, ignore_errors=True) lines = output.splitlines() known_host_entries = list(_parse_openssh_output(lines, fingerprint_hash_type=fingerprint_hash_type)) return known_host_entries if known_host_entries else None
[ "def", "recv_known_host_entries", "(", "hostname", ",", "enc", "=", "None", ",", "port", "=", "None", ",", "hash_known_hosts", "=", "True", ",", "timeout", "=", "5", ",", "fingerprint_hash_type", "=", "None", ")", ":", "# The following list of OSes have an old ver...
.. versionadded:: 2018.3.0 Retrieve information about host public keys from remote server hostname The name of the remote host (e.g. "github.com") enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss port Optional parameter, denoting the port of the remote host on which an SSH daemon is running. By default the port 22 is used. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. fingerprint_hash_type The fingerprint hash type that the public key fingerprints were originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` CLI Example: .. code-block:: bash salt '*' ssh.recv_known_host_entries <hostname> enc=<enc> port=<port>
[ "..", "versionadded", "::", "2018", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L877-L963
train
saltstack/salt
salt/modules/ssh.py
check_known_host
def check_known_host(user=None, hostname=None, key=None, fingerprint=None, config=None, port=None, fingerprint_hash_type=None): ''' Check the record in known_hosts file, either by its value or by fingerprint (it's enough to set up either key or fingerprint, you don't need to set up both). If provided key or fingerprint doesn't match with stored value, return "update", if no value is found for a given host, return "add", otherwise return "exists". If neither key, nor fingerprint is defined, then additional validation is not performed. CLI Example: .. code-block:: bash salt '*' ssh.check_known_host <user> <hostname> key='AAAA...FAaQ==' ''' if not hostname: return {'status': 'error', 'error': 'hostname argument required'} if not user: config = config or '/etc/ssh/ssh_known_hosts' else: config = config or '.ssh/known_hosts' known_host_entries = get_known_host_entries(user, hostname, config=config, port=port, fingerprint_hash_type=fingerprint_hash_type) known_keys = [h['key'] for h in known_host_entries] if known_host_entries else [] known_fingerprints = [h['fingerprint'] for h in known_host_entries] if known_host_entries else [] if not known_host_entries: return 'add' if key: return 'exists' if key in known_keys else 'update' elif fingerprint: return ('exists' if fingerprint in known_fingerprints else 'update') else: return 'exists'
python
def check_known_host(user=None, hostname=None, key=None, fingerprint=None, config=None, port=None, fingerprint_hash_type=None): ''' Check the record in known_hosts file, either by its value or by fingerprint (it's enough to set up either key or fingerprint, you don't need to set up both). If provided key or fingerprint doesn't match with stored value, return "update", if no value is found for a given host, return "add", otherwise return "exists". If neither key, nor fingerprint is defined, then additional validation is not performed. CLI Example: .. code-block:: bash salt '*' ssh.check_known_host <user> <hostname> key='AAAA...FAaQ==' ''' if not hostname: return {'status': 'error', 'error': 'hostname argument required'} if not user: config = config or '/etc/ssh/ssh_known_hosts' else: config = config or '.ssh/known_hosts' known_host_entries = get_known_host_entries(user, hostname, config=config, port=port, fingerprint_hash_type=fingerprint_hash_type) known_keys = [h['key'] for h in known_host_entries] if known_host_entries else [] known_fingerprints = [h['fingerprint'] for h in known_host_entries] if known_host_entries else [] if not known_host_entries: return 'add' if key: return 'exists' if key in known_keys else 'update' elif fingerprint: return ('exists' if fingerprint in known_fingerprints else 'update') else: return 'exists'
[ "def", "check_known_host", "(", "user", "=", "None", ",", "hostname", "=", "None", ",", "key", "=", "None", ",", "fingerprint", "=", "None", ",", "config", "=", "None", ",", "port", "=", "None", ",", "fingerprint_hash_type", "=", "None", ")", ":", "if"...
Check the record in known_hosts file, either by its value or by fingerprint (it's enough to set up either key or fingerprint, you don't need to set up both). If provided key or fingerprint doesn't match with stored value, return "update", if no value is found for a given host, return "add", otherwise return "exists". If neither key, nor fingerprint is defined, then additional validation is not performed. CLI Example: .. code-block:: bash salt '*' ssh.check_known_host <user> <hostname> key='AAAA...FAaQ=='
[ "Check", "the", "record", "in", "known_hosts", "file", "either", "by", "its", "value", "or", "by", "fingerprint", "(", "it", "s", "enough", "to", "set", "up", "either", "key", "or", "fingerprint", "you", "don", "t", "need", "to", "set", "up", "both", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L966-L1010
train
saltstack/salt
salt/modules/ssh.py
rm_known_host
def rm_known_host(user=None, hostname=None, config=None, port=None): ''' Remove all keys belonging to hostname from a known_hosts file. CLI Example: .. code-block:: bash salt '*' ssh.rm_known_host <user> <hostname> ''' if not hostname: return {'status': 'error', 'error': 'hostname argument required'} full = _get_known_hosts_file(config=config, user=user) if isinstance(full, dict): return full if not os.path.isfile(full): return {'status': 'error', 'error': 'Known hosts file {0} does not exist'.format(full)} ssh_hostname = _hostname_and_port_to_ssh_hostname(hostname, port) cmd = ['ssh-keygen', '-R', ssh_hostname, '-f', full] cmd_result = __salt__['cmd.run'](cmd, python_shell=False) if not salt.utils.platform.is_windows(): # ssh-keygen creates a new file, thus a chown is required. if os.geteuid() == 0 and user: uinfo = __salt__['user.info'](user) os.chown(full, uinfo['uid'], uinfo['gid']) return {'status': 'removed', 'comment': cmd_result}
python
def rm_known_host(user=None, hostname=None, config=None, port=None): ''' Remove all keys belonging to hostname from a known_hosts file. CLI Example: .. code-block:: bash salt '*' ssh.rm_known_host <user> <hostname> ''' if not hostname: return {'status': 'error', 'error': 'hostname argument required'} full = _get_known_hosts_file(config=config, user=user) if isinstance(full, dict): return full if not os.path.isfile(full): return {'status': 'error', 'error': 'Known hosts file {0} does not exist'.format(full)} ssh_hostname = _hostname_and_port_to_ssh_hostname(hostname, port) cmd = ['ssh-keygen', '-R', ssh_hostname, '-f', full] cmd_result = __salt__['cmd.run'](cmd, python_shell=False) if not salt.utils.platform.is_windows(): # ssh-keygen creates a new file, thus a chown is required. if os.geteuid() == 0 and user: uinfo = __salt__['user.info'](user) os.chown(full, uinfo['uid'], uinfo['gid']) return {'status': 'removed', 'comment': cmd_result}
[ "def", "rm_known_host", "(", "user", "=", "None", ",", "hostname", "=", "None", ",", "config", "=", "None", ",", "port", "=", "None", ")", ":", "if", "not", "hostname", ":", "return", "{", "'status'", ":", "'error'", ",", "'error'", ":", "'hostname arg...
Remove all keys belonging to hostname from a known_hosts file. CLI Example: .. code-block:: bash salt '*' ssh.rm_known_host <user> <hostname>
[ "Remove", "all", "keys", "belonging", "to", "hostname", "from", "a", "known_hosts", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L1013-L1044
train
saltstack/salt
salt/modules/ssh.py
set_known_host
def set_known_host(user=None, hostname=None, fingerprint=None, key=None, port=None, enc=None, config=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' Download SSH public key from remote host "hostname", optionally validate its fingerprint against "fingerprint" variable and save the record in the known_hosts file. If such a record does already exists in there, do nothing. user The user who owns the ssh authorized keys file to modify hostname The name of the remote host (e.g. "github.com") fingerprint The fingerprint of the key which must be present in the known_hosts file (optional if key specified) key The public key which must be presented in the known_hosts file (optional if fingerprint specified) port optional parameter, denoting the port of the remote host, which will be used in case, if the public key will be requested from it. By default the port 22 is used. enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. .. versionadded:: 2016.3.0 fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` CLI Example: .. code-block:: bash salt '*' ssh.set_known_host <user> fingerprint='xx:xx:..:xx' enc='ssh-rsa' config='.ssh/known_hosts' ''' if not hostname: return {'status': 'error', 'error': 'hostname argument required'} update_required = False check_required = False stored_host_entries = get_known_host_entries(user, hostname, config=config, port=port, fingerprint_hash_type=fingerprint_hash_type) stored_keys = [h['key'] for h in stored_host_entries] if stored_host_entries else [] stored_fingerprints = [h['fingerprint'] for h in stored_host_entries] if stored_host_entries else [] if not stored_host_entries: update_required = True elif fingerprint and fingerprint not in stored_fingerprints: update_required = True elif key and key not in stored_keys: update_required = True elif key is None and fingerprint is None: check_required = True if not update_required and not check_required: return {'status': 'exists', 'keys': stored_keys} if not key: remote_host_entries = recv_known_host_entries(hostname, enc=enc, port=port, hash_known_hosts=hash_known_hosts, timeout=timeout, fingerprint_hash_type=fingerprint_hash_type) known_keys = [h['key'] for h in remote_host_entries] if remote_host_entries else [] known_fingerprints = [h['fingerprint'] for h in remote_host_entries] if remote_host_entries else [] if not remote_host_entries: return {'status': 'error', 'error': 'Unable to receive remote host keys'} if fingerprint and fingerprint not in known_fingerprints: return {'status': 'error', 'error': ('Remote host public keys found but none of their ' 'fingerprints match the one you have provided')} if check_required: for key in known_keys: if key in stored_keys: return {'status': 'exists', 'keys': stored_keys} full = _get_known_hosts_file(config=config, user=user) if isinstance(full, dict): return full if os.path.isfile(full): origmode = os.stat(full).st_mode # remove existing known_host entry with matching hostname and encryption key type # use ssh-keygen -F to find the specific line(s) for this host + enc combo ssh_hostname = _hostname_and_port_to_ssh_hostname(hostname, port) cmd = ['ssh-keygen', '-F', ssh_hostname, '-f', full] lines = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False).splitlines() remove_lines = list( _get_matched_host_line_numbers(lines, enc) ) if remove_lines: try: with salt.utils.files.fopen(full, 'r+') as ofile: known_hosts_lines = salt.utils.data.decode(list(ofile)) # Delete from last line to first to avoid invalidating earlier indexes for line_no in sorted(remove_lines, reverse=True): del known_hosts_lines[line_no - 1] # Write out changed known_hosts file ofile.seek(0) ofile.truncate() ofile.writelines( salt.utils.data.decode(known_hosts_lines, to_str=True) ) except (IOError, OSError) as exception: raise CommandExecutionError( "Couldn't remove old entry(ies) from known hosts file: '{0}'".format(exception) ) else: origmode = None # set up new value if key: remote_host_entries = [{'hostname': hostname, 'enc': enc, 'key': key}] lines = [] for entry in remote_host_entries: if hash_known_hosts or port in [DEFAULT_SSH_PORT, None] or ':' in entry['hostname']: line = '{hostname} {enc} {key}\n'.format(**entry) else: entry['port'] = port line = '[{hostname}]:{port} {enc} {key}\n'.format(**entry) lines.append(line) # ensure ~/.ssh exists ssh_dir = os.path.dirname(full) if user: uinfo = __salt__['user.info'](user) try: log.debug('Ensuring ssh config dir "%s" exists', ssh_dir) os.makedirs(ssh_dir) except OSError as exc: if exc.args[1] == 'Permission denied': log.error('Unable to create directory %s: ' '%s', ssh_dir, exc.args[1]) elif exc.args[1] == 'File exists': log.debug('%s already exists, no need to create ' 'it', ssh_dir) else: # set proper ownership/permissions if user: os.chown(ssh_dir, uinfo['uid'], uinfo['gid']) os.chmod(ssh_dir, 0o700) # write line to known_hosts file try: with salt.utils.files.fopen(full, 'ab') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exception: raise CommandExecutionError( "Couldn't append to known hosts file: '{0}'".format(exception) ) if not salt.utils.platform.is_windows(): if os.geteuid() == 0 and user: os.chown(full, uinfo['uid'], uinfo['gid']) if origmode: os.chmod(full, origmode) else: os.chmod(full, 0o600) if key and hash_known_hosts: cmd_result = __salt__['ssh.hash_known_hosts'](user=user, config=full) rval = {'status': 'updated', 'old': stored_host_entries, 'new': remote_host_entries} return rval
python
def set_known_host(user=None, hostname=None, fingerprint=None, key=None, port=None, enc=None, config=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' Download SSH public key from remote host "hostname", optionally validate its fingerprint against "fingerprint" variable and save the record in the known_hosts file. If such a record does already exists in there, do nothing. user The user who owns the ssh authorized keys file to modify hostname The name of the remote host (e.g. "github.com") fingerprint The fingerprint of the key which must be present in the known_hosts file (optional if key specified) key The public key which must be presented in the known_hosts file (optional if fingerprint specified) port optional parameter, denoting the port of the remote host, which will be used in case, if the public key will be requested from it. By default the port 22 is used. enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. .. versionadded:: 2016.3.0 fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` CLI Example: .. code-block:: bash salt '*' ssh.set_known_host <user> fingerprint='xx:xx:..:xx' enc='ssh-rsa' config='.ssh/known_hosts' ''' if not hostname: return {'status': 'error', 'error': 'hostname argument required'} update_required = False check_required = False stored_host_entries = get_known_host_entries(user, hostname, config=config, port=port, fingerprint_hash_type=fingerprint_hash_type) stored_keys = [h['key'] for h in stored_host_entries] if stored_host_entries else [] stored_fingerprints = [h['fingerprint'] for h in stored_host_entries] if stored_host_entries else [] if not stored_host_entries: update_required = True elif fingerprint and fingerprint not in stored_fingerprints: update_required = True elif key and key not in stored_keys: update_required = True elif key is None and fingerprint is None: check_required = True if not update_required and not check_required: return {'status': 'exists', 'keys': stored_keys} if not key: remote_host_entries = recv_known_host_entries(hostname, enc=enc, port=port, hash_known_hosts=hash_known_hosts, timeout=timeout, fingerprint_hash_type=fingerprint_hash_type) known_keys = [h['key'] for h in remote_host_entries] if remote_host_entries else [] known_fingerprints = [h['fingerprint'] for h in remote_host_entries] if remote_host_entries else [] if not remote_host_entries: return {'status': 'error', 'error': 'Unable to receive remote host keys'} if fingerprint and fingerprint not in known_fingerprints: return {'status': 'error', 'error': ('Remote host public keys found but none of their ' 'fingerprints match the one you have provided')} if check_required: for key in known_keys: if key in stored_keys: return {'status': 'exists', 'keys': stored_keys} full = _get_known_hosts_file(config=config, user=user) if isinstance(full, dict): return full if os.path.isfile(full): origmode = os.stat(full).st_mode # remove existing known_host entry with matching hostname and encryption key type # use ssh-keygen -F to find the specific line(s) for this host + enc combo ssh_hostname = _hostname_and_port_to_ssh_hostname(hostname, port) cmd = ['ssh-keygen', '-F', ssh_hostname, '-f', full] lines = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False).splitlines() remove_lines = list( _get_matched_host_line_numbers(lines, enc) ) if remove_lines: try: with salt.utils.files.fopen(full, 'r+') as ofile: known_hosts_lines = salt.utils.data.decode(list(ofile)) # Delete from last line to first to avoid invalidating earlier indexes for line_no in sorted(remove_lines, reverse=True): del known_hosts_lines[line_no - 1] # Write out changed known_hosts file ofile.seek(0) ofile.truncate() ofile.writelines( salt.utils.data.decode(known_hosts_lines, to_str=True) ) except (IOError, OSError) as exception: raise CommandExecutionError( "Couldn't remove old entry(ies) from known hosts file: '{0}'".format(exception) ) else: origmode = None # set up new value if key: remote_host_entries = [{'hostname': hostname, 'enc': enc, 'key': key}] lines = [] for entry in remote_host_entries: if hash_known_hosts or port in [DEFAULT_SSH_PORT, None] or ':' in entry['hostname']: line = '{hostname} {enc} {key}\n'.format(**entry) else: entry['port'] = port line = '[{hostname}]:{port} {enc} {key}\n'.format(**entry) lines.append(line) # ensure ~/.ssh exists ssh_dir = os.path.dirname(full) if user: uinfo = __salt__['user.info'](user) try: log.debug('Ensuring ssh config dir "%s" exists', ssh_dir) os.makedirs(ssh_dir) except OSError as exc: if exc.args[1] == 'Permission denied': log.error('Unable to create directory %s: ' '%s', ssh_dir, exc.args[1]) elif exc.args[1] == 'File exists': log.debug('%s already exists, no need to create ' 'it', ssh_dir) else: # set proper ownership/permissions if user: os.chown(ssh_dir, uinfo['uid'], uinfo['gid']) os.chmod(ssh_dir, 0o700) # write line to known_hosts file try: with salt.utils.files.fopen(full, 'ab') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exception: raise CommandExecutionError( "Couldn't append to known hosts file: '{0}'".format(exception) ) if not salt.utils.platform.is_windows(): if os.geteuid() == 0 and user: os.chown(full, uinfo['uid'], uinfo['gid']) if origmode: os.chmod(full, origmode) else: os.chmod(full, 0o600) if key and hash_known_hosts: cmd_result = __salt__['ssh.hash_known_hosts'](user=user, config=full) rval = {'status': 'updated', 'old': stored_host_entries, 'new': remote_host_entries} return rval
[ "def", "set_known_host", "(", "user", "=", "None", ",", "hostname", "=", "None", ",", "fingerprint", "=", "None", ",", "key", "=", "None", ",", "port", "=", "None", ",", "enc", "=", "None", ",", "config", "=", "None", ",", "hash_known_hosts", "=", "T...
Download SSH public key from remote host "hostname", optionally validate its fingerprint against "fingerprint" variable and save the record in the known_hosts file. If such a record does already exists in there, do nothing. user The user who owns the ssh authorized keys file to modify hostname The name of the remote host (e.g. "github.com") fingerprint The fingerprint of the key which must be present in the known_hosts file (optional if key specified) key The public key which must be presented in the known_hosts file (optional if fingerprint specified) port optional parameter, denoting the port of the remote host, which will be used in case, if the public key will be requested from it. By default the port 22 is used. enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. .. versionadded:: 2016.3.0 fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` CLI Example: .. code-block:: bash salt '*' ssh.set_known_host <user> fingerprint='xx:xx:..:xx' enc='ssh-rsa' config='.ssh/known_hosts'
[ "Download", "SSH", "public", "key", "from", "remote", "host", "hostname", "optionally", "validate", "its", "fingerprint", "against", "fingerprint", "variable", "and", "save", "the", "record", "in", "the", "known_hosts", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L1047-L1260
train
saltstack/salt
salt/utils/boto3mod.py
_option
def _option(value): ''' Look up the value for an option. ''' if value in __opts__: return __opts__[value] master_opts = __pillar__.get('master', {}) if value in master_opts: return master_opts[value] if value in __pillar__: return __pillar__[value]
python
def _option(value): ''' Look up the value for an option. ''' if value in __opts__: return __opts__[value] master_opts = __pillar__.get('master', {}) if value in master_opts: return master_opts[value] if value in __pillar__: return __pillar__[value]
[ "def", "_option", "(", "value", ")", ":", "if", "value", "in", "__opts__", ":", "return", "__opts__", "[", "value", "]", "master_opts", "=", "__pillar__", ".", "get", "(", "'master'", ",", "{", "}", ")", "if", "value", "in", "master_opts", ":", "return...
Look up the value for an option.
[ "Look", "up", "the", "value", "for", "an", "option", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/boto3mod.py#L83-L93
train
saltstack/salt
salt/utils/boto3mod.py
get_connection
def get_connection(service, module=None, region=None, key=None, keyid=None, profile=None): ''' Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile') ''' module = module or service cxkey, region, key, keyid = _get_profile(service, region, key, keyid, profile) cxkey = cxkey + ':conn3' if cxkey in __context__: return __context__[cxkey] try: session = boto3.session.Session(aws_access_key_id=keyid, aws_secret_access_key=key, region_name=region) if session is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) conn = session.client(module) if conn is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) except boto.exception.NoAuthHandlerFound: raise SaltInvocationError('No authentication credentials found when ' 'attempting to make boto {0} connection to ' 'region "{1}".'.format(service, region)) __context__[cxkey] = conn return conn
python
def get_connection(service, module=None, region=None, key=None, keyid=None, profile=None): ''' Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile') ''' module = module or service cxkey, region, key, keyid = _get_profile(service, region, key, keyid, profile) cxkey = cxkey + ':conn3' if cxkey in __context__: return __context__[cxkey] try: session = boto3.session.Session(aws_access_key_id=keyid, aws_secret_access_key=key, region_name=region) if session is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) conn = session.client(module) if conn is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) except boto.exception.NoAuthHandlerFound: raise SaltInvocationError('No authentication credentials found when ' 'attempting to make boto {0} connection to ' 'region "{1}".'.format(service, region)) __context__[cxkey] = conn return conn
[ "def", "get_connection", "(", "service", ",", "module", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "module", "=", "module", "or", "service", "cxkey", ",", "regio...
Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile')
[ "Return", "a", "boto", "connection", "for", "the", "service", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/boto3mod.py#L181-L216
train
saltstack/salt
salt/utils/boto3mod.py
get_region
def get_region(service, region, profile): """ Retrieve the region for a particular AWS service based on configured region and/or profile. """ _, region, _, _ = _get_profile(service, region, None, None, profile) return region
python
def get_region(service, region, profile): """ Retrieve the region for a particular AWS service based on configured region and/or profile. """ _, region, _, _ = _get_profile(service, region, None, None, profile) return region
[ "def", "get_region", "(", "service", ",", "region", ",", "profile", ")", ":", "_", ",", "region", ",", "_", ",", "_", "=", "_get_profile", "(", "service", ",", "region", ",", "None", ",", "None", ",", "profile", ")", "return", "region" ]
Retrieve the region for a particular AWS service based on configured region and/or profile.
[ "Retrieve", "the", "region", "for", "a", "particular", "AWS", "service", "based", "on", "configured", "region", "and", "/", "or", "profile", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/boto3mod.py#L231-L237
train
saltstack/salt
salt/utils/boto3mod.py
assign_funcs
def assign_funcs(modname, service, module=None, get_conn_funcname='_get_conn', cache_id_funcname='_cache_id', exactly_one_funcname='_exactly_one'): ''' Assign _get_conn and _cache_id functions to the named module. .. code-block:: python _utils__['boto.assign_partials'](__name__, 'ec2') ''' mod = sys.modules[modname] setattr(mod, get_conn_funcname, get_connection_func(service, module=module)) setattr(mod, cache_id_funcname, cache_id_func(service)) # TODO: Remove this and import salt.utils.data.exactly_one into boto_* modules instead # Leaving this way for now so boto modules can be back ported if exactly_one_funcname is not None: setattr(mod, exactly_one_funcname, exactly_one)
python
def assign_funcs(modname, service, module=None, get_conn_funcname='_get_conn', cache_id_funcname='_cache_id', exactly_one_funcname='_exactly_one'): ''' Assign _get_conn and _cache_id functions to the named module. .. code-block:: python _utils__['boto.assign_partials'](__name__, 'ec2') ''' mod = sys.modules[modname] setattr(mod, get_conn_funcname, get_connection_func(service, module=module)) setattr(mod, cache_id_funcname, cache_id_func(service)) # TODO: Remove this and import salt.utils.data.exactly_one into boto_* modules instead # Leaving this way for now so boto modules can be back ported if exactly_one_funcname is not None: setattr(mod, exactly_one_funcname, exactly_one)
[ "def", "assign_funcs", "(", "modname", ",", "service", ",", "module", "=", "None", ",", "get_conn_funcname", "=", "'_get_conn'", ",", "cache_id_funcname", "=", "'_cache_id'", ",", "exactly_one_funcname", "=", "'_exactly_one'", ")", ":", "mod", "=", "sys", ".", ...
Assign _get_conn and _cache_id functions to the named module. .. code-block:: python _utils__['boto.assign_partials'](__name__, 'ec2')
[ "Assign", "_get_conn", "and", "_cache_id", "functions", "to", "the", "named", "module", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/boto3mod.py#L284-L301
train
saltstack/salt
salt/utils/boto3mod.py
paged_call
def paged_call(function, *args, **kwargs): """Retrieve full set of values from a boto3 API call that may truncate its results, yielding each page as it is obtained. """ marker_flag = kwargs.pop('marker_flag', 'NextMarker') marker_arg = kwargs.pop('marker_arg', 'Marker') while True: ret = function(*args, **kwargs) marker = ret.get(marker_flag) yield ret if not marker: break kwargs[marker_arg] = marker
python
def paged_call(function, *args, **kwargs): """Retrieve full set of values from a boto3 API call that may truncate its results, yielding each page as it is obtained. """ marker_flag = kwargs.pop('marker_flag', 'NextMarker') marker_arg = kwargs.pop('marker_arg', 'Marker') while True: ret = function(*args, **kwargs) marker = ret.get(marker_flag) yield ret if not marker: break kwargs[marker_arg] = marker
[ "def", "paged_call", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "marker_flag", "=", "kwargs", ".", "pop", "(", "'marker_flag'", ",", "'NextMarker'", ")", "marker_arg", "=", "kwargs", ".", "pop", "(", "'marker_arg'", ",", "'Mark...
Retrieve full set of values from a boto3 API call that may truncate its results, yielding each page as it is obtained.
[ "Retrieve", "full", "set", "of", "values", "from", "a", "boto3", "API", "call", "that", "may", "truncate", "its", "results", "yielding", "each", "page", "as", "it", "is", "obtained", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/boto3mod.py#L304-L316
train
saltstack/salt
salt/modules/win_path.py
_normalize_dir
def _normalize_dir(string_): ''' Normalize the directory to make comparison possible ''' return os.path.normpath(salt.utils.stringutils.to_unicode(string_))
python
def _normalize_dir(string_): ''' Normalize the directory to make comparison possible ''' return os.path.normpath(salt.utils.stringutils.to_unicode(string_))
[ "def", "_normalize_dir", "(", "string_", ")", ":", "return", "os", ".", "path", ".", "normpath", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "string_", ")", ")" ]
Normalize the directory to make comparison possible
[ "Normalize", "the", "directory", "to", "make", "comparison", "possible" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_path.py#L48-L52
train
saltstack/salt
salt/modules/win_path.py
get_path
def get_path(): ''' Returns a list of items in the SYSTEM path CLI Example: .. code-block:: bash salt '*' win_path.get_path ''' ret = salt.utils.stringutils.to_unicode( __utils__['reg.read_value']( 'HKEY_LOCAL_MACHINE', 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', 'PATH')['vdata'] ).split(';') # Trim ending backslash return list(map(_normalize_dir, ret))
python
def get_path(): ''' Returns a list of items in the SYSTEM path CLI Example: .. code-block:: bash salt '*' win_path.get_path ''' ret = salt.utils.stringutils.to_unicode( __utils__['reg.read_value']( 'HKEY_LOCAL_MACHINE', 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', 'PATH')['vdata'] ).split(';') # Trim ending backslash return list(map(_normalize_dir, ret))
[ "def", "get_path", "(", ")", ":", "ret", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "__utils__", "[", "'reg.read_value'", "]", "(", "'HKEY_LOCAL_MACHINE'", ",", "'SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Environment'", ","...
Returns a list of items in the SYSTEM path CLI Example: .. code-block:: bash salt '*' win_path.get_path
[ "Returns", "a", "list", "of", "items", "in", "the", "SYSTEM", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_path.py#L76-L94
train
saltstack/salt
salt/modules/win_path.py
exists
def exists(path): ''' Check if the directory is configured in the SYSTEM path Case-insensitive and ignores trailing backslash Returns: boolean True if path exists, False if not CLI Example: .. code-block:: bash salt '*' win_path.exists 'c:\\python27' salt '*' win_path.exists 'c:\\python27\\' salt '*' win_path.exists 'C:\\pyThon27' ''' path = _normalize_dir(path) sysPath = get_path() return path.lower() in (x.lower() for x in sysPath)
python
def exists(path): ''' Check if the directory is configured in the SYSTEM path Case-insensitive and ignores trailing backslash Returns: boolean True if path exists, False if not CLI Example: .. code-block:: bash salt '*' win_path.exists 'c:\\python27' salt '*' win_path.exists 'c:\\python27\\' salt '*' win_path.exists 'C:\\pyThon27' ''' path = _normalize_dir(path) sysPath = get_path() return path.lower() in (x.lower() for x in sysPath)
[ "def", "exists", "(", "path", ")", ":", "path", "=", "_normalize_dir", "(", "path", ")", "sysPath", "=", "get_path", "(", ")", "return", "path", ".", "lower", "(", ")", "in", "(", "x", ".", "lower", "(", ")", "for", "x", "in", "sysPath", ")" ]
Check if the directory is configured in the SYSTEM path Case-insensitive and ignores trailing backslash Returns: boolean True if path exists, False if not CLI Example: .. code-block:: bash salt '*' win_path.exists 'c:\\python27' salt '*' win_path.exists 'c:\\python27\\' salt '*' win_path.exists 'C:\\pyThon27'
[ "Check", "if", "the", "directory", "is", "configured", "in", "the", "SYSTEM", "path", "Case", "-", "insensitive", "and", "ignores", "trailing", "backslash" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_path.py#L97-L116
train
saltstack/salt
salt/modules/win_path.py
add
def add(path, index=None, **kwargs): ''' Add the directory to the SYSTEM path in the index location. Returns ``True`` if successful, otherwise ``False``. path Directory to add to path index Optionally specify an index at which to insert the directory rehash : True If the registry was updated, and this value is set to ``True``, sends a WM_SETTINGCHANGE broadcast to refresh the environment variables. Set this to ``False`` to skip this broadcast. CLI Examples: .. code-block:: bash # Will add to the beginning of the path salt '*' win_path.add 'c:\\python27' 0 # Will add to the end of the path salt '*' win_path.add 'c:\\python27' index='-1' ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) rehash_ = kwargs.pop('rehash', True) if kwargs: salt.utils.args.invalid_kwargs(kwargs) path = _normalize_dir(path) path_str = salt.utils.stringutils.to_str(path) system_path = get_path() # The current path should not have any unicode in it, but don't take any # chances. local_path = [ salt.utils.stringutils.to_str(x) for x in os.environ['PATH'].split(PATHSEP) ] if index is not None: try: index = int(index) except (TypeError, ValueError): index = None def _check_path(dirs, path, index): ''' Check the dir list for the specified path, at the specified index, and make changes to the list if needed. Return True if changes were made to the list, otherwise return False. ''' dirs_lc = [x.lower() for x in dirs] try: # Check index with case normalized cur_index = dirs_lc.index(path.lower()) except ValueError: cur_index = None num_dirs = len(dirs) # if pos is None, we don't care about where the directory is in the # PATH. If it is a number, then that number is the index to be used for # insertion (this number will be different from the index if the index # is less than -1, for reasons explained in the comments below). If it # is the string 'END', then the directory must be at the end of the # PATH, so it should be removed before appending if it is anywhere but # the end. pos = index if index is not None: if index >= num_dirs or index == -1: # Set pos to 'END' so we know that we're moving the directory # if it exists and isn't already at the end. pos = 'END' elif index <= -num_dirs: # Negative index is too large, shift index to beginning of list index = pos = 0 elif index < 0: # Negative indexes (other than -1 which is handled above) must # be inserted at index + 1 for the item to end up in the # position you want, since list.insert() inserts before the # index passed to it. For example: # # >>> x = ['one', 'two', 'four', 'five'] # >>> x.insert(-3, 'three') # >>> x # ['one', 'three', 'two', 'four', 'five'] # >>> x = ['one', 'two', 'four', 'five'] # >>> x.insert(-2, 'three') # >>> x # ['one', 'two', 'three', 'four', 'five'] pos += 1 if pos == 'END': if cur_index is not None: if cur_index == num_dirs - 1: # Directory is already in the desired location, no changes # need to be made. return False else: # Remove from current location and add it to the end dirs.pop(cur_index) dirs.append(path) return True else: # Doesn't exist in list, add it to the end dirs.append(path) return True elif index is None: # If index is None, that means that if the path is not already in # list, we will be appending it to the end instead of inserting it # somewhere in the middle. if cur_index is not None: # Directory is already in the PATH, no changes need to be made. return False else: # Directory not in the PATH, and we're not enforcing the index. # Append it to the list. dirs.append(path) return True else: if cur_index is not None: if (index < 0 and cur_index != (num_dirs + index)) \ or (index >= 0 and cur_index != index): # Directory is present, but not at the desired index. # Remove it from the non-normalized path list and insert it # at the correct postition. dirs.pop(cur_index) dirs.insert(pos, path) return True else: # Directory is present and its position matches the desired # index. No changes need to be made. return False else: # Insert the path at the desired index. dirs.insert(pos, path) return True return False if _check_path(local_path, path_str, index): _update_local_path(local_path) if not _check_path(system_path, path, index): # No changes necessary return True # Move forward with registry update result = __utils__['reg.set_value']( HIVE, KEY, VNAME, ';'.join(salt.utils.data.decode(system_path)), VTYPE ) if result and rehash_: # Broadcast WM_SETTINGCHANGE to Windows if registry was updated return rehash() else: return result
python
def add(path, index=None, **kwargs): ''' Add the directory to the SYSTEM path in the index location. Returns ``True`` if successful, otherwise ``False``. path Directory to add to path index Optionally specify an index at which to insert the directory rehash : True If the registry was updated, and this value is set to ``True``, sends a WM_SETTINGCHANGE broadcast to refresh the environment variables. Set this to ``False`` to skip this broadcast. CLI Examples: .. code-block:: bash # Will add to the beginning of the path salt '*' win_path.add 'c:\\python27' 0 # Will add to the end of the path salt '*' win_path.add 'c:\\python27' index='-1' ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) rehash_ = kwargs.pop('rehash', True) if kwargs: salt.utils.args.invalid_kwargs(kwargs) path = _normalize_dir(path) path_str = salt.utils.stringutils.to_str(path) system_path = get_path() # The current path should not have any unicode in it, but don't take any # chances. local_path = [ salt.utils.stringutils.to_str(x) for x in os.environ['PATH'].split(PATHSEP) ] if index is not None: try: index = int(index) except (TypeError, ValueError): index = None def _check_path(dirs, path, index): ''' Check the dir list for the specified path, at the specified index, and make changes to the list if needed. Return True if changes were made to the list, otherwise return False. ''' dirs_lc = [x.lower() for x in dirs] try: # Check index with case normalized cur_index = dirs_lc.index(path.lower()) except ValueError: cur_index = None num_dirs = len(dirs) # if pos is None, we don't care about where the directory is in the # PATH. If it is a number, then that number is the index to be used for # insertion (this number will be different from the index if the index # is less than -1, for reasons explained in the comments below). If it # is the string 'END', then the directory must be at the end of the # PATH, so it should be removed before appending if it is anywhere but # the end. pos = index if index is not None: if index >= num_dirs or index == -1: # Set pos to 'END' so we know that we're moving the directory # if it exists and isn't already at the end. pos = 'END' elif index <= -num_dirs: # Negative index is too large, shift index to beginning of list index = pos = 0 elif index < 0: # Negative indexes (other than -1 which is handled above) must # be inserted at index + 1 for the item to end up in the # position you want, since list.insert() inserts before the # index passed to it. For example: # # >>> x = ['one', 'two', 'four', 'five'] # >>> x.insert(-3, 'three') # >>> x # ['one', 'three', 'two', 'four', 'five'] # >>> x = ['one', 'two', 'four', 'five'] # >>> x.insert(-2, 'three') # >>> x # ['one', 'two', 'three', 'four', 'five'] pos += 1 if pos == 'END': if cur_index is not None: if cur_index == num_dirs - 1: # Directory is already in the desired location, no changes # need to be made. return False else: # Remove from current location and add it to the end dirs.pop(cur_index) dirs.append(path) return True else: # Doesn't exist in list, add it to the end dirs.append(path) return True elif index is None: # If index is None, that means that if the path is not already in # list, we will be appending it to the end instead of inserting it # somewhere in the middle. if cur_index is not None: # Directory is already in the PATH, no changes need to be made. return False else: # Directory not in the PATH, and we're not enforcing the index. # Append it to the list. dirs.append(path) return True else: if cur_index is not None: if (index < 0 and cur_index != (num_dirs + index)) \ or (index >= 0 and cur_index != index): # Directory is present, but not at the desired index. # Remove it from the non-normalized path list and insert it # at the correct postition. dirs.pop(cur_index) dirs.insert(pos, path) return True else: # Directory is present and its position matches the desired # index. No changes need to be made. return False else: # Insert the path at the desired index. dirs.insert(pos, path) return True return False if _check_path(local_path, path_str, index): _update_local_path(local_path) if not _check_path(system_path, path, index): # No changes necessary return True # Move forward with registry update result = __utils__['reg.set_value']( HIVE, KEY, VNAME, ';'.join(salt.utils.data.decode(system_path)), VTYPE ) if result and rehash_: # Broadcast WM_SETTINGCHANGE to Windows if registry was updated return rehash() else: return result
[ "def", "add", "(", "path", ",", "index", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "kwargs", ")", "rehash_", "=", "kwargs", ".", "pop", "(", "'rehash'", "...
Add the directory to the SYSTEM path in the index location. Returns ``True`` if successful, otherwise ``False``. path Directory to add to path index Optionally specify an index at which to insert the directory rehash : True If the registry was updated, and this value is set to ``True``, sends a WM_SETTINGCHANGE broadcast to refresh the environment variables. Set this to ``False`` to skip this broadcast. CLI Examples: .. code-block:: bash # Will add to the beginning of the path salt '*' win_path.add 'c:\\python27' 0 # Will add to the end of the path salt '*' win_path.add 'c:\\python27' index='-1'
[ "Add", "the", "directory", "to", "the", "SYSTEM", "path", "in", "the", "index", "location", ".", "Returns", "True", "if", "successful", "otherwise", "False", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_path.py#L123-L285
train
saltstack/salt
salt/modules/win_path.py
remove
def remove(path, **kwargs): r''' Remove the directory from the SYSTEM path Returns: boolean True if successful, False if unsuccessful rehash : True If the registry was updated, and this value is set to ``True``, sends a WM_SETTINGCHANGE broadcast to refresh the environment variables. Set this to ``False`` to skip this broadcast. CLI Example: .. code-block:: bash # Will remove C:\Python27 from the path salt '*' win_path.remove 'c:\\python27' ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) rehash_ = kwargs.pop('rehash', True) if kwargs: salt.utils.args.invalid_kwargs(kwargs) path = _normalize_dir(path) path_str = salt.utils.stringutils.to_str(path) system_path = get_path() # The current path should not have any unicode in it, but don't take any # chances. local_path = [ salt.utils.stringutils.to_str(x) for x in os.environ['PATH'].split(PATHSEP) ] def _check_path(dirs, path): ''' Check the dir list for the specified path, and make changes to the list if needed. Return True if changes were made to the list, otherwise return False. ''' dirs_lc = [x.lower() for x in dirs] path_lc = path.lower() new_dirs = [] for index, dirname in enumerate(dirs_lc): if path_lc != dirname: new_dirs.append(dirs[index]) if len(new_dirs) != len(dirs): dirs[:] = new_dirs[:] return True else: return False if _check_path(local_path, path_str): _update_local_path(local_path) if not _check_path(system_path, path): # No changes necessary return True result = __utils__['reg.set_value']( HIVE, KEY, VNAME, ';'.join(salt.utils.data.decode(system_path)), VTYPE ) if result and rehash_: # Broadcast WM_SETTINGCHANGE to Windows if registry was updated return rehash() else: return result
python
def remove(path, **kwargs): r''' Remove the directory from the SYSTEM path Returns: boolean True if successful, False if unsuccessful rehash : True If the registry was updated, and this value is set to ``True``, sends a WM_SETTINGCHANGE broadcast to refresh the environment variables. Set this to ``False`` to skip this broadcast. CLI Example: .. code-block:: bash # Will remove C:\Python27 from the path salt '*' win_path.remove 'c:\\python27' ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) rehash_ = kwargs.pop('rehash', True) if kwargs: salt.utils.args.invalid_kwargs(kwargs) path = _normalize_dir(path) path_str = salt.utils.stringutils.to_str(path) system_path = get_path() # The current path should not have any unicode in it, but don't take any # chances. local_path = [ salt.utils.stringutils.to_str(x) for x in os.environ['PATH'].split(PATHSEP) ] def _check_path(dirs, path): ''' Check the dir list for the specified path, and make changes to the list if needed. Return True if changes were made to the list, otherwise return False. ''' dirs_lc = [x.lower() for x in dirs] path_lc = path.lower() new_dirs = [] for index, dirname in enumerate(dirs_lc): if path_lc != dirname: new_dirs.append(dirs[index]) if len(new_dirs) != len(dirs): dirs[:] = new_dirs[:] return True else: return False if _check_path(local_path, path_str): _update_local_path(local_path) if not _check_path(system_path, path): # No changes necessary return True result = __utils__['reg.set_value']( HIVE, KEY, VNAME, ';'.join(salt.utils.data.decode(system_path)), VTYPE ) if result and rehash_: # Broadcast WM_SETTINGCHANGE to Windows if registry was updated return rehash() else: return result
[ "def", "remove", "(", "path", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "kwargs", ")", "rehash_", "=", "kwargs", ".", "pop", "(", "'rehash'", ",", "True", ")", "if", "...
r''' Remove the directory from the SYSTEM path Returns: boolean True if successful, False if unsuccessful rehash : True If the registry was updated, and this value is set to ``True``, sends a WM_SETTINGCHANGE broadcast to refresh the environment variables. Set this to ``False`` to skip this broadcast. CLI Example: .. code-block:: bash # Will remove C:\Python27 from the path salt '*' win_path.remove 'c:\\python27'
[ "r", "Remove", "the", "directory", "from", "the", "SYSTEM", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_path.py#L288-L361
train
saltstack/salt
salt/output/table_out.py
output
def output(ret, **kwargs): ''' Display the output as table. Args: * nested_indent: integer, specify the left alignment. * has_header: boolean specifying if header should be displayed. Default: True. * row_delimiter: character to separate rows. Default: ``_``. * delim: character to separate columns. Default: ``" | "``. * justify: text alignment. Default: ``center``. * separate_rows: boolean specifying if row separator will be displayed between consecutive rows. Default: True. * prefix: character at the beginning of the row. Default: ``"| "``. * suffix: character at the end of the row. Default: ``" |"``. * width: column max width. Default: ``50``. * rows_key: display the rows under a specific key. * labels_key: use the labels under a certain key. Otherwise will try to use the dictionary keys (if any). * title: display title when only one table is selected (using the ``rows_key`` argument). ''' # to facilitate re-use if 'opts' in kwargs: global __opts__ # pylint: disable=W0601 __opts__ = kwargs.pop('opts') # Prefer kwargs before opts base_indent = kwargs.get('nested_indent', 0) \ or __opts__.get('out.table.nested_indent', 0) rows_key = kwargs.get('rows_key') \ or __opts__.get('out.table.rows_key') labels_key = kwargs.get('labels_key') \ or __opts__.get('out.table.labels_key') title = kwargs.get('title') \ or __opts__.get('out.table.title') class_kvargs = {} argks = ('has_header', 'row_delimiter', 'delim', 'justify', 'separate_rows', 'prefix', 'suffix', 'width') for argk in argks: argv = kwargs.get(argk) \ or __opts__.get('out.table.{key}'.format(key=argk)) if argv is not None: class_kvargs[argk] = argv table = TableDisplay(**class_kvargs) out = [] if title and rows_key: out.append( table.ustring( base_indent, title, table.WHITE, # pylint: disable=no-member suffix='\n' ) ) return '\n'.join(table.display(salt.utils.data.decode(ret), base_indent, out, rows_key=rows_key, labels_key=labels_key))
python
def output(ret, **kwargs): ''' Display the output as table. Args: * nested_indent: integer, specify the left alignment. * has_header: boolean specifying if header should be displayed. Default: True. * row_delimiter: character to separate rows. Default: ``_``. * delim: character to separate columns. Default: ``" | "``. * justify: text alignment. Default: ``center``. * separate_rows: boolean specifying if row separator will be displayed between consecutive rows. Default: True. * prefix: character at the beginning of the row. Default: ``"| "``. * suffix: character at the end of the row. Default: ``" |"``. * width: column max width. Default: ``50``. * rows_key: display the rows under a specific key. * labels_key: use the labels under a certain key. Otherwise will try to use the dictionary keys (if any). * title: display title when only one table is selected (using the ``rows_key`` argument). ''' # to facilitate re-use if 'opts' in kwargs: global __opts__ # pylint: disable=W0601 __opts__ = kwargs.pop('opts') # Prefer kwargs before opts base_indent = kwargs.get('nested_indent', 0) \ or __opts__.get('out.table.nested_indent', 0) rows_key = kwargs.get('rows_key') \ or __opts__.get('out.table.rows_key') labels_key = kwargs.get('labels_key') \ or __opts__.get('out.table.labels_key') title = kwargs.get('title') \ or __opts__.get('out.table.title') class_kvargs = {} argks = ('has_header', 'row_delimiter', 'delim', 'justify', 'separate_rows', 'prefix', 'suffix', 'width') for argk in argks: argv = kwargs.get(argk) \ or __opts__.get('out.table.{key}'.format(key=argk)) if argv is not None: class_kvargs[argk] = argv table = TableDisplay(**class_kvargs) out = [] if title and rows_key: out.append( table.ustring( base_indent, title, table.WHITE, # pylint: disable=no-member suffix='\n' ) ) return '\n'.join(table.display(salt.utils.data.decode(ret), base_indent, out, rows_key=rows_key, labels_key=labels_key))
[ "def", "output", "(", "ret", ",", "*", "*", "kwargs", ")", ":", "# to facilitate re-use", "if", "'opts'", "in", "kwargs", ":", "global", "__opts__", "# pylint: disable=W0601", "__opts__", "=", "kwargs", ".", "pop", "(", "'opts'", ")", "# Prefer kwargs before opt...
Display the output as table. Args: * nested_indent: integer, specify the left alignment. * has_header: boolean specifying if header should be displayed. Default: True. * row_delimiter: character to separate rows. Default: ``_``. * delim: character to separate columns. Default: ``" | "``. * justify: text alignment. Default: ``center``. * separate_rows: boolean specifying if row separator will be displayed between consecutive rows. Default: True. * prefix: character at the beginning of the row. Default: ``"| "``. * suffix: character at the end of the row. Default: ``" |"``. * width: column max width. Default: ``50``. * rows_key: display the rows under a specific key. * labels_key: use the labels under a certain key. Otherwise will try to use the dictionary keys (if any). * title: display title when only one table is selected (using the ``rows_key`` argument).
[ "Display", "the", "output", "as", "table", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/table_out.py#L309-L370
train
saltstack/salt
salt/output/table_out.py
TableDisplay.ustring
def ustring(self, indent, color, msg, prefix='', suffix='', endc=None): '''Build the unicode string to be displayed.''' if endc is None: endc = self.ENDC # pylint: disable=no-member indent *= ' ' fmt = u'{0}{1}{2}{3}{4}{5}' try: return fmt.format(indent, color, prefix, msg, endc, suffix) except UnicodeDecodeError: return fmt.format(indent, color, prefix, salt.utils.data.decode(msg), endc, suffix)
python
def ustring(self, indent, color, msg, prefix='', suffix='', endc=None): '''Build the unicode string to be displayed.''' if endc is None: endc = self.ENDC # pylint: disable=no-member indent *= ' ' fmt = u'{0}{1}{2}{3}{4}{5}' try: return fmt.format(indent, color, prefix, msg, endc, suffix) except UnicodeDecodeError: return fmt.format(indent, color, prefix, salt.utils.data.decode(msg), endc, suffix)
[ "def", "ustring", "(", "self", ",", "indent", ",", "color", ",", "msg", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ",", "endc", "=", "None", ")", ":", "if", "endc", "is", "None", ":", "endc", "=", "self", ".", "ENDC", "# pylint: disable=no...
Build the unicode string to be displayed.
[ "Build", "the", "unicode", "string", "to", "be", "displayed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/table_out.py#L102-L119
train
saltstack/salt
salt/output/table_out.py
TableDisplay.wrap_onspace
def wrap_onspace(self, text): ''' When the text inside the column is longer then the width, will split by space and continue on the next line.''' def _truncate(line, word): return '{line}{part}{word}'.format( line=line, part=' \n'[(len(line[line.rfind('\n')+1:]) + len(word.split('\n', 1)[0]) >= self.width)], word=word ) return reduce(_truncate, text.split(' '))
python
def wrap_onspace(self, text): ''' When the text inside the column is longer then the width, will split by space and continue on the next line.''' def _truncate(line, word): return '{line}{part}{word}'.format( line=line, part=' \n'[(len(line[line.rfind('\n')+1:]) + len(word.split('\n', 1)[0]) >= self.width)], word=word ) return reduce(_truncate, text.split(' '))
[ "def", "wrap_onspace", "(", "self", ",", "text", ")", ":", "def", "_truncate", "(", "line", ",", "word", ")", ":", "return", "'{line}{part}{word}'", ".", "format", "(", "line", "=", "line", ",", "part", "=", "' \\n'", "[", "(", "len", "(", "line", "[...
When the text inside the column is longer then the width, will split by space and continue on the next line.
[ "When", "the", "text", "inside", "the", "column", "is", "longer", "then", "the", "width", "will", "split", "by", "space", "and", "continue", "on", "the", "next", "line", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/table_out.py#L121-L133
train
saltstack/salt
salt/output/table_out.py
TableDisplay.prepare_rows
def prepare_rows(self, rows, indent, has_header): '''Prepare rows content to be displayed.''' out = [] def row_wrapper(row): new_rows = [ self.wrapfunc(item).split('\n') for item in row ] rows = [] for item in map(lambda *args: args, *new_rows): if isinstance(item, (tuple, list)): rows.append([substr or '' for substr in item]) else: rows.append([item]) return rows logical_rows = [ row_wrapper(row) for row in rows ] columns = map(lambda *args: args, *reduce(operator.add, logical_rows)) max_widths = [ max([len(six.text_type(item)) for item in column]) for column in columns ] row_separator = self.row_delimiter * (len(self.prefix) + len(self.suffix) + sum(max_widths) + len(self.delim) * (len(max_widths) - 1)) justify = self._JUSTIFY_MAP[self.justify.lower()] if self.separate_rows: out.append( self.ustring( indent, self.LIGHT_GRAY, # pylint: disable=no-member row_separator ) ) for physical_rows in logical_rows: for row in physical_rows: line = self.prefix \ + self.delim.join([ justify(six.text_type(item), width) for (item, width) in zip(row, max_widths) ]) + self.suffix out.append( self.ustring( indent, self.WHITE, # pylint: disable=no-member line ) ) if self.separate_rows or has_header: out.append( self.ustring( indent, self.LIGHT_GRAY, # pylint: disable=no-member row_separator ) ) has_header = False return out
python
def prepare_rows(self, rows, indent, has_header): '''Prepare rows content to be displayed.''' out = [] def row_wrapper(row): new_rows = [ self.wrapfunc(item).split('\n') for item in row ] rows = [] for item in map(lambda *args: args, *new_rows): if isinstance(item, (tuple, list)): rows.append([substr or '' for substr in item]) else: rows.append([item]) return rows logical_rows = [ row_wrapper(row) for row in rows ] columns = map(lambda *args: args, *reduce(operator.add, logical_rows)) max_widths = [ max([len(six.text_type(item)) for item in column]) for column in columns ] row_separator = self.row_delimiter * (len(self.prefix) + len(self.suffix) + sum(max_widths) + len(self.delim) * (len(max_widths) - 1)) justify = self._JUSTIFY_MAP[self.justify.lower()] if self.separate_rows: out.append( self.ustring( indent, self.LIGHT_GRAY, # pylint: disable=no-member row_separator ) ) for physical_rows in logical_rows: for row in physical_rows: line = self.prefix \ + self.delim.join([ justify(six.text_type(item), width) for (item, width) in zip(row, max_widths) ]) + self.suffix out.append( self.ustring( indent, self.WHITE, # pylint: disable=no-member line ) ) if self.separate_rows or has_header: out.append( self.ustring( indent, self.LIGHT_GRAY, # pylint: disable=no-member row_separator ) ) has_header = False return out
[ "def", "prepare_rows", "(", "self", ",", "rows", ",", "indent", ",", "has_header", ")", ":", "out", "=", "[", "]", "def", "row_wrapper", "(", "row", ")", ":", "new_rows", "=", "[", "self", ".", "wrapfunc", "(", "item", ")", ".", "split", "(", "'\\n...
Prepare rows content to be displayed.
[ "Prepare", "rows", "content", "to", "be", "displayed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/table_out.py#L135-L204
train
saltstack/salt
salt/output/table_out.py
TableDisplay.display_rows
def display_rows(self, rows, labels, indent): '''Prepares row content and displays.''' out = [] if not rows: return out first_row_type = type(rows[0]) # all rows must have the same datatype consistent = True for row in rows[1:]: if type(row) != first_row_type: consistent = False if not consistent: return out if isinstance(labels, dict): labels_temp = [] for key in sorted(labels): labels_temp.append(labels[key]) labels = labels_temp if first_row_type is dict: # and all the others temp_rows = [] if not labels: labels = [six.text_type(label).replace('_', ' ').title() for label in sorted(rows[0])] for row in rows: temp_row = [] for key in sorted(row): temp_row.append(six.text_type(row[key])) temp_rows.append(temp_row) rows = temp_rows elif isinstance(rows[0], six.string_types): rows = [[row] for row in rows] # encapsulate each row in a single-element list labels_and_rows = [labels] + rows if labels else rows has_header = self.has_header and labels return self.prepare_rows(labels_and_rows, indent + 4, has_header)
python
def display_rows(self, rows, labels, indent): '''Prepares row content and displays.''' out = [] if not rows: return out first_row_type = type(rows[0]) # all rows must have the same datatype consistent = True for row in rows[1:]: if type(row) != first_row_type: consistent = False if not consistent: return out if isinstance(labels, dict): labels_temp = [] for key in sorted(labels): labels_temp.append(labels[key]) labels = labels_temp if first_row_type is dict: # and all the others temp_rows = [] if not labels: labels = [six.text_type(label).replace('_', ' ').title() for label in sorted(rows[0])] for row in rows: temp_row = [] for key in sorted(row): temp_row.append(six.text_type(row[key])) temp_rows.append(temp_row) rows = temp_rows elif isinstance(rows[0], six.string_types): rows = [[row] for row in rows] # encapsulate each row in a single-element list labels_and_rows = [labels] + rows if labels else rows has_header = self.has_header and labels return self.prepare_rows(labels_and_rows, indent + 4, has_header)
[ "def", "display_rows", "(", "self", ",", "rows", ",", "labels", ",", "indent", ")", ":", "out", "=", "[", "]", "if", "not", "rows", ":", "return", "out", "first_row_type", "=", "type", "(", "rows", "[", "0", "]", ")", "# all rows must have the same datat...
Prepares row content and displays.
[ "Prepares", "row", "content", "and", "displays", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/table_out.py#L206-L250
train
saltstack/salt
salt/output/table_out.py
TableDisplay.display
def display(self, ret, indent, out, rows_key=None, labels_key=None): '''Display table(s).''' rows = [] labels = None if isinstance(ret, dict): if not rows_key or (rows_key and rows_key in list(ret.keys())): # either not looking for a specific key # either looking and found in the current root for key in sorted(ret): if rows_key and key != rows_key: continue # if searching specifics, ignore anything else val = ret[key] if not rows_key: out.append( self.ustring( indent, self.DARK_GRAY, # pylint: disable=no-member key, suffix=':' ) ) out.append( self.ustring( indent, self.DARK_GRAY, # pylint: disable=no-member '----------' ) ) if isinstance(val, (list, tuple)): rows = val if labels_key: # at the same depth labels = ret.get(labels_key) # if any out.extend(self.display_rows(rows, labels, indent)) else: self.display(val, indent + 4, out, rows_key=rows_key, labels_key=labels_key) elif rows_key: # dig deeper for key in sorted(ret): val = ret[key] self.display(val, indent, out, rows_key=rows_key, labels_key=labels_key) # same indent elif isinstance(ret, (list, tuple)): if not rows_key: rows = ret out.extend(self.display_rows(rows, labels, indent)) return out
python
def display(self, ret, indent, out, rows_key=None, labels_key=None): '''Display table(s).''' rows = [] labels = None if isinstance(ret, dict): if not rows_key or (rows_key and rows_key in list(ret.keys())): # either not looking for a specific key # either looking and found in the current root for key in sorted(ret): if rows_key and key != rows_key: continue # if searching specifics, ignore anything else val = ret[key] if not rows_key: out.append( self.ustring( indent, self.DARK_GRAY, # pylint: disable=no-member key, suffix=':' ) ) out.append( self.ustring( indent, self.DARK_GRAY, # pylint: disable=no-member '----------' ) ) if isinstance(val, (list, tuple)): rows = val if labels_key: # at the same depth labels = ret.get(labels_key) # if any out.extend(self.display_rows(rows, labels, indent)) else: self.display(val, indent + 4, out, rows_key=rows_key, labels_key=labels_key) elif rows_key: # dig deeper for key in sorted(ret): val = ret[key] self.display(val, indent, out, rows_key=rows_key, labels_key=labels_key) # same indent elif isinstance(ret, (list, tuple)): if not rows_key: rows = ret out.extend(self.display_rows(rows, labels, indent)) return out
[ "def", "display", "(", "self", ",", "ret", ",", "indent", ",", "out", ",", "rows_key", "=", "None", ",", "labels_key", "=", "None", ")", ":", "rows", "=", "[", "]", "labels", "=", "None", "if", "isinstance", "(", "ret", ",", "dict", ")", ":", "if...
Display table(s).
[ "Display", "table", "(", "s", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/table_out.py#L252-L306
train
saltstack/salt
salt/states/zfs.py
_absent
def _absent(name, dataset_type, force=False, recursive=False, recursive_all=False): ''' internal shared function for *_absent name : string name of dataset dataset_type : string [filesystem, volume, snapshot, or bookmark] type of dataset to remove force : boolean try harder to destroy the dataset recursive : boolean also destroy all the child datasets recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R) ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## log configuration dataset_type = dataset_type.lower() log.debug('zfs.%s_absent::%s::config::force = %s', dataset_type, name, force) log.debug('zfs.%s_absent::%s::config::recursive = %s', dataset_type, name, recursive) ## destroy dataset if needed if __salt__['zfs.exists'](name, **{'type': dataset_type}): ## NOTE: dataset found with the name and dataset_type if not __opts__['test']: mod_res = __salt__['zfs.destroy'](name, **{'force': force, 'recursive': recursive, 'recursive_all': recursive_all}) else: mod_res = OrderedDict([('destroyed', True)]) ret['result'] = mod_res['destroyed'] if ret['result']: ret['changes'][name] = 'destroyed' ret['comment'] = '{0} {1} was destroyed'.format( dataset_type, name, ) else: ret['comment'] = 'failed to destroy {0} {1}'.format( dataset_type, name, ) if 'error' in mod_res: ret['comment'] = mod_res['error'] else: ## NOTE: no dataset found with name of the dataset_type ret['comment'] = '{0} {1} is absent'.format( dataset_type, name ) return ret
python
def _absent(name, dataset_type, force=False, recursive=False, recursive_all=False): ''' internal shared function for *_absent name : string name of dataset dataset_type : string [filesystem, volume, snapshot, or bookmark] type of dataset to remove force : boolean try harder to destroy the dataset recursive : boolean also destroy all the child datasets recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R) ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## log configuration dataset_type = dataset_type.lower() log.debug('zfs.%s_absent::%s::config::force = %s', dataset_type, name, force) log.debug('zfs.%s_absent::%s::config::recursive = %s', dataset_type, name, recursive) ## destroy dataset if needed if __salt__['zfs.exists'](name, **{'type': dataset_type}): ## NOTE: dataset found with the name and dataset_type if not __opts__['test']: mod_res = __salt__['zfs.destroy'](name, **{'force': force, 'recursive': recursive, 'recursive_all': recursive_all}) else: mod_res = OrderedDict([('destroyed', True)]) ret['result'] = mod_res['destroyed'] if ret['result']: ret['changes'][name] = 'destroyed' ret['comment'] = '{0} {1} was destroyed'.format( dataset_type, name, ) else: ret['comment'] = 'failed to destroy {0} {1}'.format( dataset_type, name, ) if 'error' in mod_res: ret['comment'] = mod_res['error'] else: ## NOTE: no dataset found with name of the dataset_type ret['comment'] = '{0} {1} is absent'.format( dataset_type, name ) return ret
[ "def", "_absent", "(", "name", ",", "dataset_type", ",", "force", "=", "False", ",", "recursive", "=", "False", ",", "recursive_all", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":...
internal shared function for *_absent name : string name of dataset dataset_type : string [filesystem, volume, snapshot, or bookmark] type of dataset to remove force : boolean try harder to destroy the dataset recursive : boolean also destroy all the child datasets recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R)
[ "internal", "shared", "function", "for", "*", "_absent" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L77-L135
train
saltstack/salt
salt/states/zfs.py
filesystem_absent
def filesystem_absent(name, force=False, recursive=False): ''' ensure filesystem is absent on the system name : string name of filesystem force : boolean try harder to destroy the dataset (zfs destroy -f) recursive : boolean also destroy all the child datasets (zfs destroy -r) .. warning:: If a volume with ``name`` exists, this state will succeed without destroying the volume specified by ``name``. This module is dataset type sensitive. ''' if not __utils__['zfs.is_dataset'](name): ret = {'name': name, 'changes': {}, 'result': False, 'comment': 'invalid dataset name: {0}'.format(name)} else: ret = _absent(name, 'filesystem', force, recursive) return ret
python
def filesystem_absent(name, force=False, recursive=False): ''' ensure filesystem is absent on the system name : string name of filesystem force : boolean try harder to destroy the dataset (zfs destroy -f) recursive : boolean also destroy all the child datasets (zfs destroy -r) .. warning:: If a volume with ``name`` exists, this state will succeed without destroying the volume specified by ``name``. This module is dataset type sensitive. ''' if not __utils__['zfs.is_dataset'](name): ret = {'name': name, 'changes': {}, 'result': False, 'comment': 'invalid dataset name: {0}'.format(name)} else: ret = _absent(name, 'filesystem', force, recursive) return ret
[ "def", "filesystem_absent", "(", "name", ",", "force", "=", "False", ",", "recursive", "=", "False", ")", ":", "if", "not", "__utils__", "[", "'zfs.is_dataset'", "]", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":",...
ensure filesystem is absent on the system name : string name of filesystem force : boolean try harder to destroy the dataset (zfs destroy -f) recursive : boolean also destroy all the child datasets (zfs destroy -r) .. warning:: If a volume with ``name`` exists, this state will succeed without destroying the volume specified by ``name``. This module is dataset type sensitive.
[ "ensure", "filesystem", "is", "absent", "on", "the", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L138-L162
train
saltstack/salt
salt/states/zfs.py
snapshot_absent
def snapshot_absent(name, force=False, recursive=False, recursive_all=False): ''' ensure snapshot is absent on the system name : string name of snapshot force : boolean try harder to destroy the dataset (zfs destroy -f) recursive : boolean also destroy all the child datasets (zfs destroy -r) recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R) ''' if not __utils__['zfs.is_snapshot'](name): ret = {'name': name, 'changes': {}, 'result': False, 'comment': 'invalid snapshot name: {0}'.format(name)} else: ret = _absent(name, 'snapshot', force, recursive, recursive_all) return ret
python
def snapshot_absent(name, force=False, recursive=False, recursive_all=False): ''' ensure snapshot is absent on the system name : string name of snapshot force : boolean try harder to destroy the dataset (zfs destroy -f) recursive : boolean also destroy all the child datasets (zfs destroy -r) recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R) ''' if not __utils__['zfs.is_snapshot'](name): ret = {'name': name, 'changes': {}, 'result': False, 'comment': 'invalid snapshot name: {0}'.format(name)} else: ret = _absent(name, 'snapshot', force, recursive, recursive_all) return ret
[ "def", "snapshot_absent", "(", "name", ",", "force", "=", "False", ",", "recursive", "=", "False", ",", "recursive_all", "=", "False", ")", ":", "if", "not", "__utils__", "[", "'zfs.is_snapshot'", "]", "(", "name", ")", ":", "ret", "=", "{", "'name'", ...
ensure snapshot is absent on the system name : string name of snapshot force : boolean try harder to destroy the dataset (zfs destroy -f) recursive : boolean also destroy all the child datasets (zfs destroy -r) recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R)
[ "ensure", "snapshot", "is", "absent", "on", "the", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L192-L214
train
saltstack/salt
salt/states/zfs.py
hold_absent
def hold_absent(name, snapshot, recursive=False): ''' ensure hold is absent on the system name : string name of hold snapshot : string name of snapshot recursive : boolean recursively releases a hold with the given tag on the snapshots of all descendent file systems. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## log configuration log.debug('zfs.hold_absent::%s::config::snapshot = %s', name, snapshot) log.debug('zfs.hold_absent::%s::config::recursive = %s', name, recursive) ## check we have a snapshot/tag name if not __utils__['zfs.is_snapshot'](snapshot): ret['result'] = False ret['comment'] = 'invalid snapshot name: {0}'.format(snapshot) return ret if __utils__['zfs.is_snapshot'](name) or \ __utils__['zfs.is_bookmark'](name) or \ name == 'error': ret['result'] = False ret['comment'] = 'invalid tag name: {0}'.format(name) return ret ## release hold if required holds = __salt__['zfs.holds'](snapshot) if name in holds: ## NOTE: hold found for snapshot, release it if not __opts__['test']: mod_res = __salt__['zfs.release'](name, snapshot, **{'recursive': recursive}) else: mod_res = OrderedDict([('released', True)]) ret['result'] = mod_res['released'] if ret['result']: ret['changes'] = {snapshot: {name: 'released'}} ret['comment'] = 'hold {0} released'.format( name, ) else: ret['comment'] = 'failed to release hold {0}'.format( name, ) if 'error' in mod_res: ret['comment'] = mod_res['error'] elif 'error' in holds: ## NOTE: we have an error ret['result'] = False ret['comment'] = holds['error'] else: ## NOTE: no hold found with name for snapshot ret['comment'] = 'hold {0} is absent'.format( name, ) return ret
python
def hold_absent(name, snapshot, recursive=False): ''' ensure hold is absent on the system name : string name of hold snapshot : string name of snapshot recursive : boolean recursively releases a hold with the given tag on the snapshots of all descendent file systems. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## log configuration log.debug('zfs.hold_absent::%s::config::snapshot = %s', name, snapshot) log.debug('zfs.hold_absent::%s::config::recursive = %s', name, recursive) ## check we have a snapshot/tag name if not __utils__['zfs.is_snapshot'](snapshot): ret['result'] = False ret['comment'] = 'invalid snapshot name: {0}'.format(snapshot) return ret if __utils__['zfs.is_snapshot'](name) or \ __utils__['zfs.is_bookmark'](name) or \ name == 'error': ret['result'] = False ret['comment'] = 'invalid tag name: {0}'.format(name) return ret ## release hold if required holds = __salt__['zfs.holds'](snapshot) if name in holds: ## NOTE: hold found for snapshot, release it if not __opts__['test']: mod_res = __salt__['zfs.release'](name, snapshot, **{'recursive': recursive}) else: mod_res = OrderedDict([('released', True)]) ret['result'] = mod_res['released'] if ret['result']: ret['changes'] = {snapshot: {name: 'released'}} ret['comment'] = 'hold {0} released'.format( name, ) else: ret['comment'] = 'failed to release hold {0}'.format( name, ) if 'error' in mod_res: ret['comment'] = mod_res['error'] elif 'error' in holds: ## NOTE: we have an error ret['result'] = False ret['comment'] = holds['error'] else: ## NOTE: no hold found with name for snapshot ret['comment'] = 'hold {0} is absent'.format( name, ) return ret
[ "def", "hold_absent", "(", "name", ",", "snapshot", ",", "recursive", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "## log configuration...
ensure hold is absent on the system name : string name of hold snapshot : string name of snapshot recursive : boolean recursively releases a hold with the given tag on the snapshots of all descendent file systems.
[ "ensure", "hold", "is", "absent", "on", "the", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L239-L306
train
saltstack/salt
salt/states/zfs.py
_dataset_present
def _dataset_present(dataset_type, name, volume_size=None, sparse=False, create_parent=False, properties=None, cloned_from=None): ''' internal handler for filesystem_present/volume_present dataset_type : string volume or filesystem name : string name of volume volume_size : string size of volume sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the volume does not exist yet, when ``cloned_from`` is set after the volume exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run. ``volume_size`` is considered a property, so the volume's size will be corrected when the properties get updated if it differs from the original volume. The sparse parameter is ignored when using ``cloned_from``. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## fallback dataset_type to filesystem if out of range if dataset_type not in ['filesystem', 'volume']: dataset_type = 'filesystem' ## ensure properties are zfs values if volume_size: volume_size = __utils__['zfs.from_size'](volume_size) if properties: properties = __utils__['zfs.from_auto_dict'](properties) elif properties is None: properties = {} ## log configuration log.debug('zfs.%s_present::%s::config::volume_size = %s', dataset_type, name, volume_size) log.debug('zfs.%s_present::%s::config::sparse = %s', dataset_type, name, sparse) log.debug('zfs.%s_present::%s::config::create_parent = %s', dataset_type, name, create_parent) log.debug('zfs.%s_present::%s::config::cloned_from = %s', dataset_type, name, cloned_from) log.debug('zfs.%s_present::%s::config::properties = %s', dataset_type, name, properties) ## check we have valid filesystem name/volume name/clone snapshot if not __utils__['zfs.is_dataset'](name): ret['result'] = False ret['comment'] = 'invalid dataset name: {0}'.format(name) return ret if cloned_from and not __utils__['zfs.is_snapshot'](cloned_from): ret['result'] = False ret['comment'] = '{0} is not a snapshot'.format(cloned_from) return ret ## ensure dataset is in correct state ## NOTE: update the dataset if __salt__['zfs.exists'](name, **{'type': dataset_type}): ## NOTE: fetch current volume properties properties_current = __salt__['zfs.get']( name, type=dataset_type, fields='value', depth=0, parsable=True, ).get(name, OrderedDict()) ## NOTE: add volsize to properties if volume_size: properties['volsize'] = volume_size ## NOTE: build list of properties to update properties_update = [] for prop in properties: ## NOTE: skip unexisting properties if prop not in properties_current: log.warning('zfs.%s_present::%s::update - unknown property: %s', dataset_type, name, prop) continue ## NOTE: compare current and wanted value if properties_current[prop]['value'] != properties[prop]: properties_update.append(prop) ## NOTE: update pool properties for prop in properties_update: if not __opts__['test']: mod_res = __salt__['zfs.set'](name, **{prop: properties[prop]}) else: mod_res = OrderedDict([('set', True)]) if mod_res['set']: if name not in ret['changes']: ret['changes'][name] = {} ret['changes'][name][prop] = properties[prop] else: ret['result'] = False if ret['comment'] == '': ret['comment'] = 'The following properties were not updated:' ret['comment'] = '{0} {1}'.format(ret['comment'], prop) ## NOTE: update comment if ret['result'] and name in ret['changes']: ret['comment'] = '{0} {1} was updated'.format(dataset_type, name) elif ret['result']: ret['comment'] = '{0} {1} is uptodate'.format(dataset_type, name) else: ret['comment'] = '{0} {1} failed to be updated'.format(dataset_type, name) ## NOTE: create or clone the dataset else: mod_res_action = 'cloned' if cloned_from else 'created' if __opts__['test']: ## NOTE: pretend to create/clone mod_res = OrderedDict([ (mod_res_action, True), ]) elif cloned_from: ## NOTE: add volsize to properties if volume_size: properties['volsize'] = volume_size ## NOTE: clone the dataset mod_res = __salt__['zfs.clone'](cloned_from, name, **{ 'create_parent': create_parent, 'properties': properties, }) else: ## NOTE: create the dataset mod_res = __salt__['zfs.create'](name, **{ 'create_parent': create_parent, 'properties': properties, 'volume_size': volume_size, 'sparse': sparse, }) ret['result'] = mod_res[mod_res_action] if ret['result']: ret['changes'][name] = mod_res_action if properties: ret['changes'][name] = properties ret['comment'] = '{0} {1} was {2}'.format( dataset_type, name, mod_res_action, ) else: ret['comment'] = 'failed to {0} {1} {2}'.format( mod_res_action[:-1], dataset_type, name, ) if 'error' in mod_res: ret['comment'] = mod_res['error'] return ret
python
def _dataset_present(dataset_type, name, volume_size=None, sparse=False, create_parent=False, properties=None, cloned_from=None): ''' internal handler for filesystem_present/volume_present dataset_type : string volume or filesystem name : string name of volume volume_size : string size of volume sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the volume does not exist yet, when ``cloned_from`` is set after the volume exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run. ``volume_size`` is considered a property, so the volume's size will be corrected when the properties get updated if it differs from the original volume. The sparse parameter is ignored when using ``cloned_from``. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## fallback dataset_type to filesystem if out of range if dataset_type not in ['filesystem', 'volume']: dataset_type = 'filesystem' ## ensure properties are zfs values if volume_size: volume_size = __utils__['zfs.from_size'](volume_size) if properties: properties = __utils__['zfs.from_auto_dict'](properties) elif properties is None: properties = {} ## log configuration log.debug('zfs.%s_present::%s::config::volume_size = %s', dataset_type, name, volume_size) log.debug('zfs.%s_present::%s::config::sparse = %s', dataset_type, name, sparse) log.debug('zfs.%s_present::%s::config::create_parent = %s', dataset_type, name, create_parent) log.debug('zfs.%s_present::%s::config::cloned_from = %s', dataset_type, name, cloned_from) log.debug('zfs.%s_present::%s::config::properties = %s', dataset_type, name, properties) ## check we have valid filesystem name/volume name/clone snapshot if not __utils__['zfs.is_dataset'](name): ret['result'] = False ret['comment'] = 'invalid dataset name: {0}'.format(name) return ret if cloned_from and not __utils__['zfs.is_snapshot'](cloned_from): ret['result'] = False ret['comment'] = '{0} is not a snapshot'.format(cloned_from) return ret ## ensure dataset is in correct state ## NOTE: update the dataset if __salt__['zfs.exists'](name, **{'type': dataset_type}): ## NOTE: fetch current volume properties properties_current = __salt__['zfs.get']( name, type=dataset_type, fields='value', depth=0, parsable=True, ).get(name, OrderedDict()) ## NOTE: add volsize to properties if volume_size: properties['volsize'] = volume_size ## NOTE: build list of properties to update properties_update = [] for prop in properties: ## NOTE: skip unexisting properties if prop not in properties_current: log.warning('zfs.%s_present::%s::update - unknown property: %s', dataset_type, name, prop) continue ## NOTE: compare current and wanted value if properties_current[prop]['value'] != properties[prop]: properties_update.append(prop) ## NOTE: update pool properties for prop in properties_update: if not __opts__['test']: mod_res = __salt__['zfs.set'](name, **{prop: properties[prop]}) else: mod_res = OrderedDict([('set', True)]) if mod_res['set']: if name not in ret['changes']: ret['changes'][name] = {} ret['changes'][name][prop] = properties[prop] else: ret['result'] = False if ret['comment'] == '': ret['comment'] = 'The following properties were not updated:' ret['comment'] = '{0} {1}'.format(ret['comment'], prop) ## NOTE: update comment if ret['result'] and name in ret['changes']: ret['comment'] = '{0} {1} was updated'.format(dataset_type, name) elif ret['result']: ret['comment'] = '{0} {1} is uptodate'.format(dataset_type, name) else: ret['comment'] = '{0} {1} failed to be updated'.format(dataset_type, name) ## NOTE: create or clone the dataset else: mod_res_action = 'cloned' if cloned_from else 'created' if __opts__['test']: ## NOTE: pretend to create/clone mod_res = OrderedDict([ (mod_res_action, True), ]) elif cloned_from: ## NOTE: add volsize to properties if volume_size: properties['volsize'] = volume_size ## NOTE: clone the dataset mod_res = __salt__['zfs.clone'](cloned_from, name, **{ 'create_parent': create_parent, 'properties': properties, }) else: ## NOTE: create the dataset mod_res = __salt__['zfs.create'](name, **{ 'create_parent': create_parent, 'properties': properties, 'volume_size': volume_size, 'sparse': sparse, }) ret['result'] = mod_res[mod_res_action] if ret['result']: ret['changes'][name] = mod_res_action if properties: ret['changes'][name] = properties ret['comment'] = '{0} {1} was {2}'.format( dataset_type, name, mod_res_action, ) else: ret['comment'] = 'failed to {0} {1} {2}'.format( mod_res_action[:-1], dataset_type, name, ) if 'error' in mod_res: ret['comment'] = mod_res['error'] return ret
[ "def", "_dataset_present", "(", "dataset_type", ",", "name", ",", "volume_size", "=", "None", ",", "sparse", "=", "False", ",", "create_parent", "=", "False", ",", "properties", "=", "None", ",", "cloned_from", "=", "None", ")", ":", "ret", "=", "{", "'n...
internal handler for filesystem_present/volume_present dataset_type : string volume or filesystem name : string name of volume volume_size : string size of volume sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the volume does not exist yet, when ``cloned_from`` is set after the volume exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run. ``volume_size`` is considered a property, so the volume's size will be corrected when the properties get updated if it differs from the original volume. The sparse parameter is ignored when using ``cloned_from``.
[ "internal", "handler", "for", "filesystem_present", "/", "volume_present" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L382-L557
train
saltstack/salt
salt/states/zfs.py
filesystem_present
def filesystem_present(name, create_parent=False, properties=None, cloned_from=None): ''' ensure filesystem exists and has properties set name : string name of filesystem create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the filesystem does not exist yet, when ``cloned_from`` is set after the filesystem exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run. ''' return _dataset_present( 'filesystem', name, create_parent=create_parent, properties=properties, cloned_from=cloned_from, )
python
def filesystem_present(name, create_parent=False, properties=None, cloned_from=None): ''' ensure filesystem exists and has properties set name : string name of filesystem create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the filesystem does not exist yet, when ``cloned_from`` is set after the filesystem exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run. ''' return _dataset_present( 'filesystem', name, create_parent=create_parent, properties=properties, cloned_from=cloned_from, )
[ "def", "filesystem_present", "(", "name", ",", "create_parent", "=", "False", ",", "properties", "=", "None", ",", "cloned_from", "=", "None", ")", ":", "return", "_dataset_present", "(", "'filesystem'", ",", "name", ",", "create_parent", "=", "create_parent", ...
ensure filesystem exists and has properties set name : string name of filesystem create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the filesystem does not exist yet, when ``cloned_from`` is set after the filesystem exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run.
[ "ensure", "filesystem", "exists", "and", "has", "properties", "set" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L560-L589
train
saltstack/salt
salt/states/zfs.py
volume_present
def volume_present(name, volume_size, sparse=False, create_parent=False, properties=None, cloned_from=None): ''' ensure volume exists and has properties set name : string name of volume volume_size : string size of volume sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the volume does not exist yet, when ``cloned_from`` is set after the volume exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run. ``volume_size`` is considered a property, so the volume's size will be corrected when the properties get updated if it differs from the original volume. The sparse parameter is ignored when using ``cloned_from``. ''' return _dataset_present( 'volume', name, volume_size, sparse=sparse, create_parent=create_parent, properties=properties, cloned_from=cloned_from, )
python
def volume_present(name, volume_size, sparse=False, create_parent=False, properties=None, cloned_from=None): ''' ensure volume exists and has properties set name : string name of volume volume_size : string size of volume sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the volume does not exist yet, when ``cloned_from`` is set after the volume exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run. ``volume_size`` is considered a property, so the volume's size will be corrected when the properties get updated if it differs from the original volume. The sparse parameter is ignored when using ``cloned_from``. ''' return _dataset_present( 'volume', name, volume_size, sparse=sparse, create_parent=create_parent, properties=properties, cloned_from=cloned_from, )
[ "def", "volume_present", "(", "name", ",", "volume_size", ",", "sparse", "=", "False", ",", "create_parent", "=", "False", ",", "properties", "=", "None", ",", "cloned_from", "=", "None", ")", ":", "return", "_dataset_present", "(", "'volume'", ",", "name", ...
ensure volume exists and has properties set name : string name of volume volume_size : string size of volume sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. cloned_from : string name of snapshot to clone properties : dict additional zfs properties (-o) .. note:: ``cloned_from`` is only use if the volume does not exist yet, when ``cloned_from`` is set after the volume exists it will be ignored. .. note:: Properties do not get cloned, if you specify the properties in the state file they will be applied on a subsequent run. ``volume_size`` is considered a property, so the volume's size will be corrected when the properties get updated if it differs from the original volume. The sparse parameter is ignored when using ``cloned_from``.
[ "ensure", "volume", "exists", "and", "has", "properties", "set" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L592-L633
train
saltstack/salt
salt/states/zfs.py
bookmark_present
def bookmark_present(name, snapshot): ''' ensure bookmark exists name : string name of bookmark snapshot : string name of snapshot ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## log configuration log.debug('zfs.bookmark_present::%s::config::snapshot = %s', name, snapshot) ## check we have valid snapshot/bookmark name if not __utils__['zfs.is_snapshot'](snapshot): ret['result'] = False ret['comment'] = 'invalid snapshot name: {0}'.format(name) return ret if '#' not in name and '/' not in name: ## NOTE: simple snapshot name # take the snapshot name and replace the snapshot but with the simple name # e.g. pool/fs@snap + bm --> pool/fs#bm name = '{0}#{1}'.format(snapshot[:snapshot.index('@')], name) ret['name'] = name if not __utils__['zfs.is_bookmark'](name): ret['result'] = False ret['comment'] = 'invalid bookmark name: {0}'.format(name) return ret ## ensure bookmark exists if not __salt__['zfs.exists'](name, **{'type': 'bookmark'}): ## NOTE: bookmark the snapshot if not __opts__['test']: mod_res = __salt__['zfs.bookmark'](snapshot, name) else: mod_res = OrderedDict([('bookmarked', True)]) ret['result'] = mod_res['bookmarked'] if ret['result']: ret['changes'][name] = snapshot ret['comment'] = '{0} bookmarked as {1}'.format(snapshot, name) else: ret['comment'] = 'failed to bookmark {0}'.format(snapshot) if 'error' in mod_res: ret['comment'] = mod_res['error'] else: ## NOTE: bookmark already exists ret['comment'] = 'bookmark is present' return ret
python
def bookmark_present(name, snapshot): ''' ensure bookmark exists name : string name of bookmark snapshot : string name of snapshot ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## log configuration log.debug('zfs.bookmark_present::%s::config::snapshot = %s', name, snapshot) ## check we have valid snapshot/bookmark name if not __utils__['zfs.is_snapshot'](snapshot): ret['result'] = False ret['comment'] = 'invalid snapshot name: {0}'.format(name) return ret if '#' not in name and '/' not in name: ## NOTE: simple snapshot name # take the snapshot name and replace the snapshot but with the simple name # e.g. pool/fs@snap + bm --> pool/fs#bm name = '{0}#{1}'.format(snapshot[:snapshot.index('@')], name) ret['name'] = name if not __utils__['zfs.is_bookmark'](name): ret['result'] = False ret['comment'] = 'invalid bookmark name: {0}'.format(name) return ret ## ensure bookmark exists if not __salt__['zfs.exists'](name, **{'type': 'bookmark'}): ## NOTE: bookmark the snapshot if not __opts__['test']: mod_res = __salt__['zfs.bookmark'](snapshot, name) else: mod_res = OrderedDict([('bookmarked', True)]) ret['result'] = mod_res['bookmarked'] if ret['result']: ret['changes'][name] = snapshot ret['comment'] = '{0} bookmarked as {1}'.format(snapshot, name) else: ret['comment'] = 'failed to bookmark {0}'.format(snapshot) if 'error' in mod_res: ret['comment'] = mod_res['error'] else: ## NOTE: bookmark already exists ret['comment'] = 'bookmark is present' return ret
[ "def", "bookmark_present", "(", "name", ",", "snapshot", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "## log configuration", "log", ".", "debug", "("...
ensure bookmark exists name : string name of bookmark snapshot : string name of snapshot
[ "ensure", "bookmark", "exists" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L636-L693
train
saltstack/salt
salt/states/zfs.py
snapshot_present
def snapshot_present(name, recursive=False, properties=None): ''' ensure snapshot exists and has properties set name : string name of snapshot recursive : boolean recursively create snapshots of all descendent datasets properties : dict additional zfs properties (-o) .. note: Properties are only set at creation time ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## log configuration log.debug('zfs.snapshot_present::%s::config::recursive = %s', name, recursive) log.debug('zfs.snapshot_present::%s::config::properties = %s', name, properties) ## ensure properties are zfs values if properties: properties = __utils__['zfs.from_auto_dict'](properties) ## check we have valid snapshot name if not __utils__['zfs.is_snapshot'](name): ret['result'] = False ret['comment'] = 'invalid snapshot name: {0}'.format(name) return ret ## ensure snapshot exits if not __salt__['zfs.exists'](name, **{'type': 'snapshot'}): ## NOTE: create the snapshot if not __opts__['test']: mod_res = __salt__['zfs.snapshot'](name, **{'recursive': recursive, 'properties': properties}) else: mod_res = OrderedDict([('snapshotted', True)]) ret['result'] = mod_res['snapshotted'] if ret['result']: ret['changes'][name] = 'snapshotted' if properties: ret['changes'][name] = properties ret['comment'] = 'snapshot {0} was created'.format(name) else: ret['comment'] = 'failed to create snapshot {0}'.format(name) if 'error' in mod_res: ret['comment'] = mod_res['error'] else: ## NOTE: snapshot already exists ret['comment'] = 'snapshot is present' return ret
python
def snapshot_present(name, recursive=False, properties=None): ''' ensure snapshot exists and has properties set name : string name of snapshot recursive : boolean recursively create snapshots of all descendent datasets properties : dict additional zfs properties (-o) .. note: Properties are only set at creation time ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## log configuration log.debug('zfs.snapshot_present::%s::config::recursive = %s', name, recursive) log.debug('zfs.snapshot_present::%s::config::properties = %s', name, properties) ## ensure properties are zfs values if properties: properties = __utils__['zfs.from_auto_dict'](properties) ## check we have valid snapshot name if not __utils__['zfs.is_snapshot'](name): ret['result'] = False ret['comment'] = 'invalid snapshot name: {0}'.format(name) return ret ## ensure snapshot exits if not __salt__['zfs.exists'](name, **{'type': 'snapshot'}): ## NOTE: create the snapshot if not __opts__['test']: mod_res = __salt__['zfs.snapshot'](name, **{'recursive': recursive, 'properties': properties}) else: mod_res = OrderedDict([('snapshotted', True)]) ret['result'] = mod_res['snapshotted'] if ret['result']: ret['changes'][name] = 'snapshotted' if properties: ret['changes'][name] = properties ret['comment'] = 'snapshot {0} was created'.format(name) else: ret['comment'] = 'failed to create snapshot {0}'.format(name) if 'error' in mod_res: ret['comment'] = mod_res['error'] else: ## NOTE: snapshot already exists ret['comment'] = 'snapshot is present' return ret
[ "def", "snapshot_present", "(", "name", ",", "recursive", "=", "False", ",", "properties", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}",...
ensure snapshot exists and has properties set name : string name of snapshot recursive : boolean recursively create snapshots of all descendent datasets properties : dict additional zfs properties (-o) .. note: Properties are only set at creation time
[ "ensure", "snapshot", "exists", "and", "has", "properties", "set" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L696-L754
train
saltstack/salt
salt/states/zfs.py
promoted
def promoted(name): ''' ensure a dataset is not a clone name : string name of fileset or volume .. warning:: only one dataset can be the origin, if you promote a clone the original will now point to the promoted dataset ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## check we if we have a valid dataset name if not __utils__['zfs.is_dataset'](name): ret['result'] = False ret['comment'] = 'invalid dataset name: {0}'.format(name) return ret ## ensure dataset is the primary instance if not __salt__['zfs.exists'](name, **{'type': 'filesystem,volume'}): ## NOTE: we don't have a dataset ret['result'] = False ret['comment'] = 'dataset {0} does not exist'.format(name) else: ## NOTE: check if we have a blank origin (-) if __salt__['zfs.get'](name, **{'properties': 'origin', 'fields': 'value', 'parsable': True})[name]['origin']['value'] == '-': ## NOTE: we're already promoted ret['comment'] = '{0} already promoted'.format(name) else: ## NOTE: promote dataset if not __opts__['test']: mod_res = __salt__['zfs.promote'](name) else: mod_res = OrderedDict([('promoted', True)]) ret['result'] = mod_res['promoted'] if ret['result']: ret['changes'][name] = 'promoted' ret['comment'] = '{0} promoted'.format(name) else: ret['comment'] = 'failed to promote {0}'.format(name) if 'error' in mod_res: ret['comment'] = mod_res['error'] return ret
python
def promoted(name): ''' ensure a dataset is not a clone name : string name of fileset or volume .. warning:: only one dataset can be the origin, if you promote a clone the original will now point to the promoted dataset ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## check we if we have a valid dataset name if not __utils__['zfs.is_dataset'](name): ret['result'] = False ret['comment'] = 'invalid dataset name: {0}'.format(name) return ret ## ensure dataset is the primary instance if not __salt__['zfs.exists'](name, **{'type': 'filesystem,volume'}): ## NOTE: we don't have a dataset ret['result'] = False ret['comment'] = 'dataset {0} does not exist'.format(name) else: ## NOTE: check if we have a blank origin (-) if __salt__['zfs.get'](name, **{'properties': 'origin', 'fields': 'value', 'parsable': True})[name]['origin']['value'] == '-': ## NOTE: we're already promoted ret['comment'] = '{0} already promoted'.format(name) else: ## NOTE: promote dataset if not __opts__['test']: mod_res = __salt__['zfs.promote'](name) else: mod_res = OrderedDict([('promoted', True)]) ret['result'] = mod_res['promoted'] if ret['result']: ret['changes'][name] = 'promoted' ret['comment'] = '{0} promoted'.format(name) else: ret['comment'] = 'failed to promote {0}'.format(name) if 'error' in mod_res: ret['comment'] = mod_res['error'] return ret
[ "def", "promoted", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "## check we if we have a valid dataset name", "if", "not", "__utils__", "[",...
ensure a dataset is not a clone name : string name of fileset or volume .. warning:: only one dataset can be the origin, if you promote a clone the original will now point to the promoted dataset
[ "ensure", "a", "dataset", "is", "not", "a", "clone" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L757-L807
train
saltstack/salt
salt/states/zfs.py
_schedule_snapshot_retrieve
def _schedule_snapshot_retrieve(dataset, prefix, snapshots): ''' Update snapshots dict with current snapshots dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : OrderedDict preseeded OrderedDict with configuration ''' ## NOTE: retrieve all snapshots for the dataset for snap in sorted(__salt__['zfs.list'](dataset, **{'recursive': True, 'depth': 1, 'type': 'snapshot'}).keys()): ## NOTE: we only want the actualy name ## myzpool/data@zbck-20171201_000248 -> zbck-20171201_000248 snap_name = snap[snap.index('@')+1:] ## NOTE: we only want snapshots matching our prefix if not snap_name.startswith('{0}-'.format(prefix)): continue ## NOTE: retrieve the holds for this snapshot snap_holds = __salt__['zfs.holds'](snap) ## NOTE: this snapshot has no holds, eligable for pruning if not snap_holds: snapshots['_prunable'].append(snap) ## NOTE: update snapshots based on holds (if any) ## we are only interested in the ones from our schedule ## if we find any others we skip them for hold in snap_holds: if hold in snapshots['_schedule'].keys(): snapshots[hold].append(snap) return snapshots
python
def _schedule_snapshot_retrieve(dataset, prefix, snapshots): ''' Update snapshots dict with current snapshots dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : OrderedDict preseeded OrderedDict with configuration ''' ## NOTE: retrieve all snapshots for the dataset for snap in sorted(__salt__['zfs.list'](dataset, **{'recursive': True, 'depth': 1, 'type': 'snapshot'}).keys()): ## NOTE: we only want the actualy name ## myzpool/data@zbck-20171201_000248 -> zbck-20171201_000248 snap_name = snap[snap.index('@')+1:] ## NOTE: we only want snapshots matching our prefix if not snap_name.startswith('{0}-'.format(prefix)): continue ## NOTE: retrieve the holds for this snapshot snap_holds = __salt__['zfs.holds'](snap) ## NOTE: this snapshot has no holds, eligable for pruning if not snap_holds: snapshots['_prunable'].append(snap) ## NOTE: update snapshots based on holds (if any) ## we are only interested in the ones from our schedule ## if we find any others we skip them for hold in snap_holds: if hold in snapshots['_schedule'].keys(): snapshots[hold].append(snap) return snapshots
[ "def", "_schedule_snapshot_retrieve", "(", "dataset", ",", "prefix", ",", "snapshots", ")", ":", "## NOTE: retrieve all snapshots for the dataset", "for", "snap", "in", "sorted", "(", "__salt__", "[", "'zfs.list'", "]", "(", "dataset", ",", "*", "*", "{", "'recurs...
Update snapshots dict with current snapshots dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : OrderedDict preseeded OrderedDict with configuration
[ "Update", "snapshots", "dict", "with", "current", "snapshots" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L810-L847
train
saltstack/salt
salt/states/zfs.py
_schedule_snapshot_prepare
def _schedule_snapshot_prepare(dataset, prefix, snapshots): ''' Update snapshots dict with info for a new snapshot dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : OrderedDict preseeded OrderedDict with configuration ''' ## NOTE: generate new snapshot name snapshot_create_name = '{dataset}@{prefix}-{timestamp}'.format( dataset=dataset, prefix=prefix, timestamp=datetime.now().strftime('%Y%m%d_%H%M%S') ) ## NOTE: figure out if we need to create the snapshot timestamp_now = datetime.now().replace(second=0, microsecond=0) snapshots['_create'][snapshot_create_name] = [] for hold, hold_count in snapshots['_schedule'].items(): ## NOTE: skip hold if we don't keep snapshots for it if hold_count == 0: continue ## NOTE: figure out if we need the current hold on the new snapshot if snapshots[hold]: ## NOTE: extract datetime from snapshot name timestamp = datetime.strptime( snapshots[hold][-1], '{0}@{1}-%Y%m%d_%H%M%S'.format(dataset, prefix), ).replace(second=0, microsecond=0) ## NOTE: compare current timestamp to timestamp from snapshot if hold == 'minute' and \ timestamp_now <= timestamp: continue elif hold == 'hour' and \ timestamp_now.replace(**comp_hour) <= timestamp.replace(**comp_hour): continue elif hold == 'day' and \ timestamp_now.replace(**comp_day) <= timestamp.replace(**comp_day): continue elif hold == 'month' and \ timestamp_now.replace(**comp_month) <= timestamp.replace(**comp_month): continue elif hold == 'year' and \ timestamp_now.replace(**comp_year) <= timestamp.replace(**comp_year): continue ## NOTE: add hold entry for snapshot snapshots['_create'][snapshot_create_name].append(hold) return snapshots
python
def _schedule_snapshot_prepare(dataset, prefix, snapshots): ''' Update snapshots dict with info for a new snapshot dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : OrderedDict preseeded OrderedDict with configuration ''' ## NOTE: generate new snapshot name snapshot_create_name = '{dataset}@{prefix}-{timestamp}'.format( dataset=dataset, prefix=prefix, timestamp=datetime.now().strftime('%Y%m%d_%H%M%S') ) ## NOTE: figure out if we need to create the snapshot timestamp_now = datetime.now().replace(second=0, microsecond=0) snapshots['_create'][snapshot_create_name] = [] for hold, hold_count in snapshots['_schedule'].items(): ## NOTE: skip hold if we don't keep snapshots for it if hold_count == 0: continue ## NOTE: figure out if we need the current hold on the new snapshot if snapshots[hold]: ## NOTE: extract datetime from snapshot name timestamp = datetime.strptime( snapshots[hold][-1], '{0}@{1}-%Y%m%d_%H%M%S'.format(dataset, prefix), ).replace(second=0, microsecond=0) ## NOTE: compare current timestamp to timestamp from snapshot if hold == 'minute' and \ timestamp_now <= timestamp: continue elif hold == 'hour' and \ timestamp_now.replace(**comp_hour) <= timestamp.replace(**comp_hour): continue elif hold == 'day' and \ timestamp_now.replace(**comp_day) <= timestamp.replace(**comp_day): continue elif hold == 'month' and \ timestamp_now.replace(**comp_month) <= timestamp.replace(**comp_month): continue elif hold == 'year' and \ timestamp_now.replace(**comp_year) <= timestamp.replace(**comp_year): continue ## NOTE: add hold entry for snapshot snapshots['_create'][snapshot_create_name].append(hold) return snapshots
[ "def", "_schedule_snapshot_prepare", "(", "dataset", ",", "prefix", ",", "snapshots", ")", ":", "## NOTE: generate new snapshot name", "snapshot_create_name", "=", "'{dataset}@{prefix}-{timestamp}'", ".", "format", "(", "dataset", "=", "dataset", ",", "prefix", "=", "pr...
Update snapshots dict with info for a new snapshot dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : OrderedDict preseeded OrderedDict with configuration
[ "Update", "snapshots", "dict", "with", "info", "for", "a", "new", "snapshot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L850-L906
train
saltstack/salt
salt/states/zfs.py
scheduled_snapshot
def scheduled_snapshot(name, prefix, recursive=True, schedule=None): ''' maintain a set of snapshots based on a schedule name : string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' recursive : boolean create snapshots for all children also schedule : dict dict holding the schedule, the following keys are available (minute, hour, day, month, and year) by default all are set to 0 the value indicated the number of snapshots of that type to keep around. .. warning:: snapshots will only be created and pruned every time the state runs. a schedule must be setup to automatically run the state. this means that if you run the state daily the hourly snapshot will only be made once per day! .. versionchanged:: 2018.3.0 switched to localtime from gmtime so times now take into account timezones. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## initialize defaults schedule_holds = ['minute', 'hour', 'day', 'month', 'year'] snapshots = OrderedDict([ ('_create', OrderedDict()), ('_prunable', []), ('_schedule', OrderedDict()), ]) ## strict configuration validation ## NOTE: we need a valid dataset if not __utils__['zfs.is_dataset'](name): ret['result'] = False ret['comment'] = 'invalid dataset name: {0}'.format(name) if not __salt__['zfs.exists'](name, **{'type': 'filesystem,volume'}): ret['comment'] = 'dataset {0} does not exist'.format(name) ret['result'] = False ## NOTE: prefix must be 4 or longer if not prefix or len(prefix) < 4: ret['comment'] = 'prefix ({0}) must be at least 4 long'.format(prefix) ret['result'] = False ## NOTE: validate schedule total_count = 0 for hold in schedule_holds: snapshots[hold] = [] if hold not in schedule: snapshots['_schedule'][hold] = 0 elif isinstance(schedule[hold], int): snapshots['_schedule'][hold] = schedule[hold] else: ret['result'] = False ret['comment'] = 'schedule value for {0} is not an integer'.format( hold, ) break total_count += snapshots['_schedule'][hold] if ret['result'] and total_count == 0: ret['result'] = False ret['comment'] = 'schedule is not valid, you need to keep atleast 1 snapshot' ## NOTE: return if configuration is not valid if not ret['result']: return ret ## retrieve existing snapshots snapshots = _schedule_snapshot_retrieve(name, prefix, snapshots) ## prepare snapshot snapshots = _schedule_snapshot_prepare(name, prefix, snapshots) ## log configuration log.debug('zfs.scheduled_snapshot::%s::config::recursive = %s', name, recursive) log.debug('zfs.scheduled_snapshot::%s::config::prefix = %s', name, prefix) log.debug('zfs.scheduled_snapshot::%s::snapshots = %s', name, snapshots) ## create snapshot(s) for snapshot_name, snapshot_holds in snapshots['_create'].items(): ## NOTE: skip if new snapshot has no holds if not snapshot_holds: continue ## NOTE: create snapshot if not __opts__['test']: mod_res = __salt__['zfs.snapshot'](snapshot_name, **{'recursive': recursive}) else: mod_res = OrderedDict([('snapshotted', True)]) if not mod_res['snapshotted']: ret['result'] = False ret['comment'] = 'error creating snapshot ({0})'.format(snapshot_name) else: ## NOTE: create holds (if we have a snapshot) for hold in snapshot_holds: if not __opts__['test']: mod_res = __salt__['zfs.hold'](hold, snapshot_name, **{'recursive': recursive}) else: mod_res = OrderedDict([('held', True)]) if not mod_res['held']: ret['result'] = False ret['comment'] = "error adding hold ({0}) to snapshot ({1})".format( hold, snapshot_name, ) break snapshots[hold].append(snapshot_name) if ret['result']: ret['comment'] = 'scheduled snapshots updated' if 'created' not in ret['changes']: ret['changes']['created'] = [] ret['changes']['created'].append(snapshot_name) ## prune hold(s) for hold, hold_count in snapshots['_schedule'].items(): while ret['result'] and len(snapshots[hold]) > hold_count: ## NOTE: pop oldest snapshot snapshot_name = snapshots[hold].pop(0) ## NOTE: release hold for snapshot if not __opts__['test']: mod_res = __salt__['zfs.release'](hold, snapshot_name, **{'recursive': recursive}) else: mod_res = OrderedDict([('released', True)]) if not mod_res['released']: ret['result'] = False ret['comment'] = "error adding hold ({0}) to snapshot ({1})".format( hold, snapshot_name, ) ## NOTE: mark as prunable if not __salt__['zfs.holds'](snapshot_name): snapshots['_prunable'].append(snapshot_name) ## prune snapshot(s) for snapshot_name in snapshots['_prunable']: ## NOTE: destroy snapshot if not __opts__['test']: mod_res = __salt__['zfs.destroy'](snapshot_name, **{'recursive': recursive}) else: mod_res = OrderedDict([('destroyed', True)]) if not mod_res['destroyed']: ret['result'] = False ret['comment'] = "error prunding snapshot ({1})".format( snapshot_name, ) break if ret['result'] and snapshots['_prunable']: ret['comment'] = 'scheduled snapshots updated' ret['changes']['pruned'] = snapshots['_prunable'] if ret['result'] and not ret['changes']: ret['comment'] = 'scheduled snapshots are up to date' return ret
python
def scheduled_snapshot(name, prefix, recursive=True, schedule=None): ''' maintain a set of snapshots based on a schedule name : string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' recursive : boolean create snapshots for all children also schedule : dict dict holding the schedule, the following keys are available (minute, hour, day, month, and year) by default all are set to 0 the value indicated the number of snapshots of that type to keep around. .. warning:: snapshots will only be created and pruned every time the state runs. a schedule must be setup to automatically run the state. this means that if you run the state daily the hourly snapshot will only be made once per day! .. versionchanged:: 2018.3.0 switched to localtime from gmtime so times now take into account timezones. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} ## initialize defaults schedule_holds = ['minute', 'hour', 'day', 'month', 'year'] snapshots = OrderedDict([ ('_create', OrderedDict()), ('_prunable', []), ('_schedule', OrderedDict()), ]) ## strict configuration validation ## NOTE: we need a valid dataset if not __utils__['zfs.is_dataset'](name): ret['result'] = False ret['comment'] = 'invalid dataset name: {0}'.format(name) if not __salt__['zfs.exists'](name, **{'type': 'filesystem,volume'}): ret['comment'] = 'dataset {0} does not exist'.format(name) ret['result'] = False ## NOTE: prefix must be 4 or longer if not prefix or len(prefix) < 4: ret['comment'] = 'prefix ({0}) must be at least 4 long'.format(prefix) ret['result'] = False ## NOTE: validate schedule total_count = 0 for hold in schedule_holds: snapshots[hold] = [] if hold not in schedule: snapshots['_schedule'][hold] = 0 elif isinstance(schedule[hold], int): snapshots['_schedule'][hold] = schedule[hold] else: ret['result'] = False ret['comment'] = 'schedule value for {0} is not an integer'.format( hold, ) break total_count += snapshots['_schedule'][hold] if ret['result'] and total_count == 0: ret['result'] = False ret['comment'] = 'schedule is not valid, you need to keep atleast 1 snapshot' ## NOTE: return if configuration is not valid if not ret['result']: return ret ## retrieve existing snapshots snapshots = _schedule_snapshot_retrieve(name, prefix, snapshots) ## prepare snapshot snapshots = _schedule_snapshot_prepare(name, prefix, snapshots) ## log configuration log.debug('zfs.scheduled_snapshot::%s::config::recursive = %s', name, recursive) log.debug('zfs.scheduled_snapshot::%s::config::prefix = %s', name, prefix) log.debug('zfs.scheduled_snapshot::%s::snapshots = %s', name, snapshots) ## create snapshot(s) for snapshot_name, snapshot_holds in snapshots['_create'].items(): ## NOTE: skip if new snapshot has no holds if not snapshot_holds: continue ## NOTE: create snapshot if not __opts__['test']: mod_res = __salt__['zfs.snapshot'](snapshot_name, **{'recursive': recursive}) else: mod_res = OrderedDict([('snapshotted', True)]) if not mod_res['snapshotted']: ret['result'] = False ret['comment'] = 'error creating snapshot ({0})'.format(snapshot_name) else: ## NOTE: create holds (if we have a snapshot) for hold in snapshot_holds: if not __opts__['test']: mod_res = __salt__['zfs.hold'](hold, snapshot_name, **{'recursive': recursive}) else: mod_res = OrderedDict([('held', True)]) if not mod_res['held']: ret['result'] = False ret['comment'] = "error adding hold ({0}) to snapshot ({1})".format( hold, snapshot_name, ) break snapshots[hold].append(snapshot_name) if ret['result']: ret['comment'] = 'scheduled snapshots updated' if 'created' not in ret['changes']: ret['changes']['created'] = [] ret['changes']['created'].append(snapshot_name) ## prune hold(s) for hold, hold_count in snapshots['_schedule'].items(): while ret['result'] and len(snapshots[hold]) > hold_count: ## NOTE: pop oldest snapshot snapshot_name = snapshots[hold].pop(0) ## NOTE: release hold for snapshot if not __opts__['test']: mod_res = __salt__['zfs.release'](hold, snapshot_name, **{'recursive': recursive}) else: mod_res = OrderedDict([('released', True)]) if not mod_res['released']: ret['result'] = False ret['comment'] = "error adding hold ({0}) to snapshot ({1})".format( hold, snapshot_name, ) ## NOTE: mark as prunable if not __salt__['zfs.holds'](snapshot_name): snapshots['_prunable'].append(snapshot_name) ## prune snapshot(s) for snapshot_name in snapshots['_prunable']: ## NOTE: destroy snapshot if not __opts__['test']: mod_res = __salt__['zfs.destroy'](snapshot_name, **{'recursive': recursive}) else: mod_res = OrderedDict([('destroyed', True)]) if not mod_res['destroyed']: ret['result'] = False ret['comment'] = "error prunding snapshot ({1})".format( snapshot_name, ) break if ret['result'] and snapshots['_prunable']: ret['comment'] = 'scheduled snapshots updated' ret['changes']['pruned'] = snapshots['_prunable'] if ret['result'] and not ret['changes']: ret['comment'] = 'scheduled snapshots are up to date' return ret
[ "def", "scheduled_snapshot", "(", "name", ",", "prefix", ",", "recursive", "=", "True", ",", "schedule", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", "...
maintain a set of snapshots based on a schedule name : string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' recursive : boolean create snapshots for all children also schedule : dict dict holding the schedule, the following keys are available (minute, hour, day, month, and year) by default all are set to 0 the value indicated the number of snapshots of that type to keep around. .. warning:: snapshots will only be created and pruned every time the state runs. a schedule must be setup to automatically run the state. this means that if you run the state daily the hourly snapshot will only be made once per day! .. versionchanged:: 2018.3.0 switched to localtime from gmtime so times now take into account timezones.
[ "maintain", "a", "set", "of", "snapshots", "based", "on", "a", "schedule" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L909-L1085
train
saltstack/salt
salt/modules/win_dacl.py
_getUserSid
def _getUserSid(user): ''' return a state error dictionary, with 'sid' as a field if it could be returned if user is None, sid will also be None ''' ret = {} sid_pattern = r'^S-1(-\d+){1,}$' if user and re.match(sid_pattern, user, re.I): try: sid = win32security.GetBinarySid(user) except Exception as e: ret['result'] = False ret['comment'] = 'Unable to obtain the binary security identifier for {0}. The exception was {1}.'.format( user, e) else: try: win32security.LookupAccountSid('', sid) ret['result'] = True ret['sid'] = sid except Exception as e: ret['result'] = False ret['comment'] = 'Unable to lookup the account for the security identifier {0}. The exception was {1}.'.format( user, e) else: try: sid = win32security.LookupAccountName('', user)[0] if user else None ret['result'] = True ret['sid'] = sid except Exception as e: ret['result'] = False ret['comment'] = 'Unable to obtain the security identifier for {0}. The exception was {1}.'.format( user, e) return ret
python
def _getUserSid(user): ''' return a state error dictionary, with 'sid' as a field if it could be returned if user is None, sid will also be None ''' ret = {} sid_pattern = r'^S-1(-\d+){1,}$' if user and re.match(sid_pattern, user, re.I): try: sid = win32security.GetBinarySid(user) except Exception as e: ret['result'] = False ret['comment'] = 'Unable to obtain the binary security identifier for {0}. The exception was {1}.'.format( user, e) else: try: win32security.LookupAccountSid('', sid) ret['result'] = True ret['sid'] = sid except Exception as e: ret['result'] = False ret['comment'] = 'Unable to lookup the account for the security identifier {0}. The exception was {1}.'.format( user, e) else: try: sid = win32security.LookupAccountName('', user)[0] if user else None ret['result'] = True ret['sid'] = sid except Exception as e: ret['result'] = False ret['comment'] = 'Unable to obtain the security identifier for {0}. The exception was {1}.'.format( user, e) return ret
[ "def", "_getUserSid", "(", "user", ")", ":", "ret", "=", "{", "}", "sid_pattern", "=", "r'^S-1(-\\d+){1,}$'", "if", "user", "and", "re", ".", "match", "(", "sid_pattern", ",", "user", ",", "re", ".", "I", ")", ":", "try", ":", "sid", "=", "win32secur...
return a state error dictionary, with 'sid' as a field if it could be returned if user is None, sid will also be None
[ "return", "a", "state", "error", "dictionary", "with", "sid", "as", "a", "field", "if", "it", "could", "be", "returned", "if", "user", "is", "None", "sid", "will", "also", "be", "None" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L304-L338
train
saltstack/salt
salt/modules/win_dacl.py
_get_dacl
def _get_dacl(path, objectType): ''' Gets the DACL of a path ''' try: dacl = win32security.GetNamedSecurityInfo( path, objectType, win32security.DACL_SECURITY_INFORMATION ).GetSecurityDescriptorDacl() except Exception: dacl = None return dacl
python
def _get_dacl(path, objectType): ''' Gets the DACL of a path ''' try: dacl = win32security.GetNamedSecurityInfo( path, objectType, win32security.DACL_SECURITY_INFORMATION ).GetSecurityDescriptorDacl() except Exception: dacl = None return dacl
[ "def", "_get_dacl", "(", "path", ",", "objectType", ")", ":", "try", ":", "dacl", "=", "win32security", ".", "GetNamedSecurityInfo", "(", "path", ",", "objectType", ",", "win32security", ".", "DACL_SECURITY_INFORMATION", ")", ".", "GetSecurityDescriptorDacl", "(",...
Gets the DACL of a path
[ "Gets", "the", "DACL", "of", "a", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L350-L360
train
saltstack/salt
salt/modules/win_dacl.py
get
def get(path, objectType, user=None): ''' Get the ACL of an object. Will filter by user if one is provided. Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: A user name to filter by Returns (dict): A dictionary containing the ACL CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.get c:\temp directory ''' ret = {'Path': path, 'ACLs': []} sidRet = _getUserSid(user) if path and objectType: dc = daclConstants() objectTypeBit = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectTypeBit) tdacl = _get_dacl(path, objectTypeBit) if tdacl: for counter in range(0, tdacl.GetAceCount()): tAce = tdacl.GetAce(counter) if not sidRet['sid'] or (tAce[2] == sidRet['sid']): ret['ACLs'].append(_ace_to_text(tAce, objectTypeBit)) return ret
python
def get(path, objectType, user=None): ''' Get the ACL of an object. Will filter by user if one is provided. Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: A user name to filter by Returns (dict): A dictionary containing the ACL CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.get c:\temp directory ''' ret = {'Path': path, 'ACLs': []} sidRet = _getUserSid(user) if path and objectType: dc = daclConstants() objectTypeBit = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectTypeBit) tdacl = _get_dacl(path, objectTypeBit) if tdacl: for counter in range(0, tdacl.GetAceCount()): tAce = tdacl.GetAce(counter) if not sidRet['sid'] or (tAce[2] == sidRet['sid']): ret['ACLs'].append(_ace_to_text(tAce, objectTypeBit)) return ret
[ "def", "get", "(", "path", ",", "objectType", ",", "user", "=", "None", ")", ":", "ret", "=", "{", "'Path'", ":", "path", ",", "'ACLs'", ":", "[", "]", "}", "sidRet", "=", "_getUserSid", "(", "user", ")", "if", "path", "and", "objectType", ":", "...
Get the ACL of an object. Will filter by user if one is provided. Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: A user name to filter by Returns (dict): A dictionary containing the ACL CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.get c:\temp directory
[ "Get", "the", "ACL", "of", "an", "object", ".", "Will", "filter", "by", "user", "if", "one", "is", "provided", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L363-L395
train
saltstack/salt
salt/modules/win_dacl.py
add_ace
def add_ace(path, objectType, user, permission, acetype, propagation): r''' add an ace to an object path: path to the object (i.e. c:\\temp\\file, HKEY_LOCAL_MACHINE\\SOFTWARE\\KEY, etc) user: user to add permission: permissions for the user acetype: either allow/deny for each user/permission (ALLOW, DENY) propagation: how the ACE applies to children for Registry Keys and Directories(KEY, KEY&SUBKEYS, SUBKEYS) CLI Example: .. code-block:: bash allow domain\fakeuser full control on HKLM\\SOFTWARE\\somekey, propagate to this key and subkeys salt 'myminion' win_dacl.add_ace 'HKEY_LOCAL_MACHINE\\SOFTWARE\\somekey' 'Registry' 'domain\fakeuser' 'FULLCONTROL' 'ALLOW' 'KEY&SUBKEYS' ''' ret = {'result': None, 'changes': {}, 'comment': ''} if (path and user and permission and acetype and propagation): if objectType.upper() == "FILE": propagation = "FILE" dc = daclConstants() objectTypeBit = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectTypeBit) user = user.strip() permission = permission.strip().upper() acetype = acetype.strip().upper() propagation = propagation.strip().upper() sidRet = _getUserSid(user) if not sidRet['result']: return sidRet permissionbit = dc.getPermissionBit(objectTypeBit, permission) acetypebit = dc.getAceTypeBit(acetype) propagationbit = dc.getPropagationBit(objectTypeBit, propagation) dacl = _get_dacl(path, objectTypeBit) if dacl: acesAdded = [] try: if acetypebit == 0: dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, propagationbit, permissionbit, sidRet['sid']) elif acetypebit == 1: dacl.AddAccessDeniedAceEx(win32security.ACL_REVISION, propagationbit, permissionbit, sidRet['sid']) win32security.SetNamedSecurityInfo( path, objectTypeBit, win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None) acesAdded.append(( '{0} {1} {2} on {3}' ).format( user, dc.getAceTypeText(acetype), dc.getPermissionText(objectTypeBit, permission), dc.getPropagationText(objectTypeBit, propagation))) ret['result'] = True except Exception as e: ret['comment'] = 'An error occurred attempting to add the ace. The error was {0}'.format(e) ret['result'] = False return ret if acesAdded: ret['changes']['Added ACEs'] = acesAdded else: ret['comment'] = 'Unable to obtain the DACL of {0}'.format(path) else: ret['comment'] = 'An empty value was specified for a required item.' ret['result'] = False return ret
python
def add_ace(path, objectType, user, permission, acetype, propagation): r''' add an ace to an object path: path to the object (i.e. c:\\temp\\file, HKEY_LOCAL_MACHINE\\SOFTWARE\\KEY, etc) user: user to add permission: permissions for the user acetype: either allow/deny for each user/permission (ALLOW, DENY) propagation: how the ACE applies to children for Registry Keys and Directories(KEY, KEY&SUBKEYS, SUBKEYS) CLI Example: .. code-block:: bash allow domain\fakeuser full control on HKLM\\SOFTWARE\\somekey, propagate to this key and subkeys salt 'myminion' win_dacl.add_ace 'HKEY_LOCAL_MACHINE\\SOFTWARE\\somekey' 'Registry' 'domain\fakeuser' 'FULLCONTROL' 'ALLOW' 'KEY&SUBKEYS' ''' ret = {'result': None, 'changes': {}, 'comment': ''} if (path and user and permission and acetype and propagation): if objectType.upper() == "FILE": propagation = "FILE" dc = daclConstants() objectTypeBit = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectTypeBit) user = user.strip() permission = permission.strip().upper() acetype = acetype.strip().upper() propagation = propagation.strip().upper() sidRet = _getUserSid(user) if not sidRet['result']: return sidRet permissionbit = dc.getPermissionBit(objectTypeBit, permission) acetypebit = dc.getAceTypeBit(acetype) propagationbit = dc.getPropagationBit(objectTypeBit, propagation) dacl = _get_dacl(path, objectTypeBit) if dacl: acesAdded = [] try: if acetypebit == 0: dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, propagationbit, permissionbit, sidRet['sid']) elif acetypebit == 1: dacl.AddAccessDeniedAceEx(win32security.ACL_REVISION, propagationbit, permissionbit, sidRet['sid']) win32security.SetNamedSecurityInfo( path, objectTypeBit, win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None) acesAdded.append(( '{0} {1} {2} on {3}' ).format( user, dc.getAceTypeText(acetype), dc.getPermissionText(objectTypeBit, permission), dc.getPropagationText(objectTypeBit, propagation))) ret['result'] = True except Exception as e: ret['comment'] = 'An error occurred attempting to add the ace. The error was {0}'.format(e) ret['result'] = False return ret if acesAdded: ret['changes']['Added ACEs'] = acesAdded else: ret['comment'] = 'Unable to obtain the DACL of {0}'.format(path) else: ret['comment'] = 'An empty value was specified for a required item.' ret['result'] = False return ret
[ "def", "add_ace", "(", "path", ",", "objectType", ",", "user", ",", "permission", ",", "acetype", ",", "propagation", ")", ":", "ret", "=", "{", "'result'", ":", "None", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "if", "(", ...
r''' add an ace to an object path: path to the object (i.e. c:\\temp\\file, HKEY_LOCAL_MACHINE\\SOFTWARE\\KEY, etc) user: user to add permission: permissions for the user acetype: either allow/deny for each user/permission (ALLOW, DENY) propagation: how the ACE applies to children for Registry Keys and Directories(KEY, KEY&SUBKEYS, SUBKEYS) CLI Example: .. code-block:: bash allow domain\fakeuser full control on HKLM\\SOFTWARE\\somekey, propagate to this key and subkeys salt 'myminion' win_dacl.add_ace 'HKEY_LOCAL_MACHINE\\SOFTWARE\\somekey' 'Registry' 'domain\fakeuser' 'FULLCONTROL' 'ALLOW' 'KEY&SUBKEYS'
[ "r", "add", "an", "ace", "to", "an", "object" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L398-L467
train
saltstack/salt
salt/modules/win_dacl.py
rm_ace
def rm_ace(path, objectType, user, permission=None, acetype=None, propagation=None): r''' remove an ace to an object path: path to the object (i.e. c:\\temp\\file, HKEY_LOCAL_MACHINE\\SOFTWARE\\KEY, etc) user: user to remove permission: permissions for the user acetypes: either allow/deny for each user/permission (ALLOW, DENY) propagation: how the ACE applies to children for Registry Keys and Directories(KEY, KEY&SUBKEYS, SUBKEYS) If any of the optional parameters are omitted (or set to None) they act as wildcards. CLI Example: .. code-block:: bash remove allow domain\fakeuser full control on HKLM\\SOFTWARE\\somekey propagated to this key and subkeys salt 'myminion' win_dacl.rm_ace 'Registry' 'HKEY_LOCAL_MACHINE\\SOFTWARE\\somekey' 'domain\fakeuser' 'FULLCONTROL' 'ALLOW' 'KEY&SUBKEYS' ''' ret = {'result': None, 'changes': {}, 'comment': ''} if path and user: dc = daclConstants() if propagation and objectType.upper() == "FILE": propagation = "FILE" objectTypeBit = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectTypeBit) user = user.strip() permission = permission.strip().upper() if permission else None acetype = acetype.strip().upper() if acetype else None propagation = propagation.strip().upper() if propagation else None if check_ace(path, objectType, user, permission, acetype, propagation, True)['Exists']: sidRet = _getUserSid(user) if not sidRet['result']: return sidRet permissionbit = dc.getPermissionBit(objectTypeBit, permission) if permission else None acetypebit = dc.getAceTypeBit(acetype) if acetype else None propagationbit = dc.getPropagationBit(objectTypeBit, propagation) if propagation else None dacl = _get_dacl(path, objectTypeBit) counter = 0 acesRemoved = [] while counter < dacl.GetAceCount(): tAce = dacl.GetAce(counter) if (tAce[0][1] & win32security.INHERITED_ACE) != win32security.INHERITED_ACE: if tAce[2] == sidRet['sid']: if not acetypebit or tAce[0][0] == acetypebit: if not propagationbit or ((tAce[0][1] & propagationbit) == propagationbit): if not permissionbit or tAce[1] == permissionbit: dacl.DeleteAce(counter) counter = counter - 1 acesRemoved.append(_ace_to_text(tAce, objectTypeBit)) counter = counter + 1 if acesRemoved: try: win32security.SetNamedSecurityInfo( path, objectTypeBit, win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None) ret['changes']['Removed ACEs'] = acesRemoved ret['result'] = True except Exception as e: ret['result'] = False ret['comment'] = 'Error removing ACE. The error was {0}.'.format(e) return ret else: ret['comment'] = 'The specified ACE was not found on the path.' return ret
python
def rm_ace(path, objectType, user, permission=None, acetype=None, propagation=None): r''' remove an ace to an object path: path to the object (i.e. c:\\temp\\file, HKEY_LOCAL_MACHINE\\SOFTWARE\\KEY, etc) user: user to remove permission: permissions for the user acetypes: either allow/deny for each user/permission (ALLOW, DENY) propagation: how the ACE applies to children for Registry Keys and Directories(KEY, KEY&SUBKEYS, SUBKEYS) If any of the optional parameters are omitted (or set to None) they act as wildcards. CLI Example: .. code-block:: bash remove allow domain\fakeuser full control on HKLM\\SOFTWARE\\somekey propagated to this key and subkeys salt 'myminion' win_dacl.rm_ace 'Registry' 'HKEY_LOCAL_MACHINE\\SOFTWARE\\somekey' 'domain\fakeuser' 'FULLCONTROL' 'ALLOW' 'KEY&SUBKEYS' ''' ret = {'result': None, 'changes': {}, 'comment': ''} if path and user: dc = daclConstants() if propagation and objectType.upper() == "FILE": propagation = "FILE" objectTypeBit = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectTypeBit) user = user.strip() permission = permission.strip().upper() if permission else None acetype = acetype.strip().upper() if acetype else None propagation = propagation.strip().upper() if propagation else None if check_ace(path, objectType, user, permission, acetype, propagation, True)['Exists']: sidRet = _getUserSid(user) if not sidRet['result']: return sidRet permissionbit = dc.getPermissionBit(objectTypeBit, permission) if permission else None acetypebit = dc.getAceTypeBit(acetype) if acetype else None propagationbit = dc.getPropagationBit(objectTypeBit, propagation) if propagation else None dacl = _get_dacl(path, objectTypeBit) counter = 0 acesRemoved = [] while counter < dacl.GetAceCount(): tAce = dacl.GetAce(counter) if (tAce[0][1] & win32security.INHERITED_ACE) != win32security.INHERITED_ACE: if tAce[2] == sidRet['sid']: if not acetypebit or tAce[0][0] == acetypebit: if not propagationbit or ((tAce[0][1] & propagationbit) == propagationbit): if not permissionbit or tAce[1] == permissionbit: dacl.DeleteAce(counter) counter = counter - 1 acesRemoved.append(_ace_to_text(tAce, objectTypeBit)) counter = counter + 1 if acesRemoved: try: win32security.SetNamedSecurityInfo( path, objectTypeBit, win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None) ret['changes']['Removed ACEs'] = acesRemoved ret['result'] = True except Exception as e: ret['result'] = False ret['comment'] = 'Error removing ACE. The error was {0}.'.format(e) return ret else: ret['comment'] = 'The specified ACE was not found on the path.' return ret
[ "def", "rm_ace", "(", "path", ",", "objectType", ",", "user", ",", "permission", "=", "None", ",", "acetype", "=", "None", ",", "propagation", "=", "None", ")", ":", "ret", "=", "{", "'result'", ":", "None", ",", "'changes'", ":", "{", "}", ",", "'...
r''' remove an ace to an object path: path to the object (i.e. c:\\temp\\file, HKEY_LOCAL_MACHINE\\SOFTWARE\\KEY, etc) user: user to remove permission: permissions for the user acetypes: either allow/deny for each user/permission (ALLOW, DENY) propagation: how the ACE applies to children for Registry Keys and Directories(KEY, KEY&SUBKEYS, SUBKEYS) If any of the optional parameters are omitted (or set to None) they act as wildcards. CLI Example: .. code-block:: bash remove allow domain\fakeuser full control on HKLM\\SOFTWARE\\somekey propagated to this key and subkeys salt 'myminion' win_dacl.rm_ace 'Registry' 'HKEY_LOCAL_MACHINE\\SOFTWARE\\somekey' 'domain\fakeuser' 'FULLCONTROL' 'ALLOW' 'KEY&SUBKEYS'
[ "r", "remove", "an", "ace", "to", "an", "object" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L470-L540
train
saltstack/salt
salt/modules/win_dacl.py
_ace_to_text
def _ace_to_text(ace, objectType): ''' helper function to convert an ace to a textual representation ''' dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) try: userSid = win32security.LookupAccountSid('', ace[2]) if userSid[1]: userSid = '{1}\\{0}'.format(userSid[0], userSid[1]) else: userSid = '{0}'.format(userSid[0]) except Exception: userSid = win32security.ConvertSidToStringSid(ace[2]) tPerm = ace[1] tAceType = ace[0][0] tProps = ace[0][1] tInherited = '' for x in dc.validAceTypes: if dc.validAceTypes[x]['BITS'] == tAceType: tAceType = dc.validAceTypes[x]['TEXT'] break for x in dc.rights[objectType]: if dc.rights[objectType][x]['BITS'] == tPerm: tPerm = dc.rights[objectType][x]['TEXT'] break if (tProps & win32security.INHERITED_ACE) == win32security.INHERITED_ACE: tInherited = '[Inherited]' tProps = (tProps ^ win32security.INHERITED_ACE) for x in dc.validPropagations[objectType]: if dc.validPropagations[objectType][x]['BITS'] == tProps: tProps = dc.validPropagations[objectType][x]['TEXT'] break return (( '{0} {1} {2} on {3} {4}' ).format(userSid, tAceType, tPerm, tProps, tInherited))
python
def _ace_to_text(ace, objectType): ''' helper function to convert an ace to a textual representation ''' dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) try: userSid = win32security.LookupAccountSid('', ace[2]) if userSid[1]: userSid = '{1}\\{0}'.format(userSid[0], userSid[1]) else: userSid = '{0}'.format(userSid[0]) except Exception: userSid = win32security.ConvertSidToStringSid(ace[2]) tPerm = ace[1] tAceType = ace[0][0] tProps = ace[0][1] tInherited = '' for x in dc.validAceTypes: if dc.validAceTypes[x]['BITS'] == tAceType: tAceType = dc.validAceTypes[x]['TEXT'] break for x in dc.rights[objectType]: if dc.rights[objectType][x]['BITS'] == tPerm: tPerm = dc.rights[objectType][x]['TEXT'] break if (tProps & win32security.INHERITED_ACE) == win32security.INHERITED_ACE: tInherited = '[Inherited]' tProps = (tProps ^ win32security.INHERITED_ACE) for x in dc.validPropagations[objectType]: if dc.validPropagations[objectType][x]['BITS'] == tProps: tProps = dc.validPropagations[objectType][x]['TEXT'] break return (( '{0} {1} {2} on {3} {4}' ).format(userSid, tAceType, tPerm, tProps, tInherited))
[ "def", "_ace_to_text", "(", "ace", ",", "objectType", ")", ":", "dc", "=", "daclConstants", "(", ")", "objectType", "=", "dc", ".", "getObjectTypeBit", "(", "objectType", ")", "try", ":", "userSid", "=", "win32security", ".", "LookupAccountSid", "(", "''", ...
helper function to convert an ace to a textual representation
[ "helper", "function", "to", "convert", "an", "ace", "to", "a", "textual", "representation" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L543-L578
train
saltstack/salt
salt/modules/win_dacl.py
_set_dacl_inheritance
def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=False): ''' helper function to set the inheritance Args: path (str): The path to the object objectType (str): The type of object inheritance (bool): True enables inheritance, False disables copy (bool): Copy inherited ACEs to the DACL before disabling inheritance clear (bool): Remove non-inherited ACEs from the DACL ''' ret = {'result': False, 'comment': '', 'changes': {}} if path: try: sd = win32security.GetNamedSecurityInfo(path, objectType, win32security.DACL_SECURITY_INFORMATION) tdacl = sd.GetSecurityDescriptorDacl() if inheritance: if clear: counter = 0 removedAces = [] while counter < tdacl.GetAceCount(): tAce = tdacl.GetAce(counter) if (tAce[0][1] & win32security.INHERITED_ACE) != win32security.INHERITED_ACE: tdacl.DeleteAce(counter) removedAces.append(_ace_to_text(tAce, objectType)) else: counter = counter + 1 if removedAces: ret['changes']['Removed ACEs'] = removedAces else: ret['changes']['Non-Inherited ACEs'] = 'Left in the DACL' win32security.SetNamedSecurityInfo( path, objectType, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, tdacl, None) ret['changes']['Inheritance'] = 'Enabled' else: if not copy: counter = 0 inheritedAcesRemoved = [] while counter < tdacl.GetAceCount(): tAce = tdacl.GetAce(counter) if (tAce[0][1] & win32security.INHERITED_ACE) == win32security.INHERITED_ACE: tdacl.DeleteAce(counter) inheritedAcesRemoved.append(_ace_to_text(tAce, objectType)) else: counter = counter + 1 if inheritedAcesRemoved: ret['changes']['Removed ACEs'] = inheritedAcesRemoved else: ret['changes']['Previously Inherited ACEs'] = 'Copied to the DACL' win32security.SetNamedSecurityInfo( path, objectType, win32security.DACL_SECURITY_INFORMATION | win32security.PROTECTED_DACL_SECURITY_INFORMATION, None, None, tdacl, None) ret['changes']['Inheritance'] = 'Disabled' ret['result'] = True except Exception as e: ret['result'] = False ret['comment'] = 'Error attempting to set the inheritance. The error was {0}.'.format(e) return ret
python
def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=False): ''' helper function to set the inheritance Args: path (str): The path to the object objectType (str): The type of object inheritance (bool): True enables inheritance, False disables copy (bool): Copy inherited ACEs to the DACL before disabling inheritance clear (bool): Remove non-inherited ACEs from the DACL ''' ret = {'result': False, 'comment': '', 'changes': {}} if path: try: sd = win32security.GetNamedSecurityInfo(path, objectType, win32security.DACL_SECURITY_INFORMATION) tdacl = sd.GetSecurityDescriptorDacl() if inheritance: if clear: counter = 0 removedAces = [] while counter < tdacl.GetAceCount(): tAce = tdacl.GetAce(counter) if (tAce[0][1] & win32security.INHERITED_ACE) != win32security.INHERITED_ACE: tdacl.DeleteAce(counter) removedAces.append(_ace_to_text(tAce, objectType)) else: counter = counter + 1 if removedAces: ret['changes']['Removed ACEs'] = removedAces else: ret['changes']['Non-Inherited ACEs'] = 'Left in the DACL' win32security.SetNamedSecurityInfo( path, objectType, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, tdacl, None) ret['changes']['Inheritance'] = 'Enabled' else: if not copy: counter = 0 inheritedAcesRemoved = [] while counter < tdacl.GetAceCount(): tAce = tdacl.GetAce(counter) if (tAce[0][1] & win32security.INHERITED_ACE) == win32security.INHERITED_ACE: tdacl.DeleteAce(counter) inheritedAcesRemoved.append(_ace_to_text(tAce, objectType)) else: counter = counter + 1 if inheritedAcesRemoved: ret['changes']['Removed ACEs'] = inheritedAcesRemoved else: ret['changes']['Previously Inherited ACEs'] = 'Copied to the DACL' win32security.SetNamedSecurityInfo( path, objectType, win32security.DACL_SECURITY_INFORMATION | win32security.PROTECTED_DACL_SECURITY_INFORMATION, None, None, tdacl, None) ret['changes']['Inheritance'] = 'Disabled' ret['result'] = True except Exception as e: ret['result'] = False ret['comment'] = 'Error attempting to set the inheritance. The error was {0}.'.format(e) return ret
[ "def", "_set_dacl_inheritance", "(", "path", ",", "objectType", ",", "inheritance", "=", "True", ",", "copy", "=", "True", ",", "clear", "=", "False", ")", ":", "ret", "=", "{", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", "...
helper function to set the inheritance Args: path (str): The path to the object objectType (str): The type of object inheritance (bool): True enables inheritance, False disables copy (bool): Copy inherited ACEs to the DACL before disabling inheritance clear (bool): Remove non-inherited ACEs from the DACL
[ "helper", "function", "to", "set", "the", "inheritance", "Args", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L581-L650
train
saltstack/salt
salt/modules/win_dacl.py
enable_inheritance
def enable_inheritance(path, objectType, clear=False): ''' enable/disable inheritance on an object Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) clear: True will remove non-Inherited ACEs from the ACL Returns (dict): A dictionary containing the results CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.enable_inheritance c:\temp directory ''' dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectType) return _set_dacl_inheritance(path, objectType, True, None, clear)
python
def enable_inheritance(path, objectType, clear=False): ''' enable/disable inheritance on an object Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) clear: True will remove non-Inherited ACEs from the ACL Returns (dict): A dictionary containing the results CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.enable_inheritance c:\temp directory ''' dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectType) return _set_dacl_inheritance(path, objectType, True, None, clear)
[ "def", "enable_inheritance", "(", "path", ",", "objectType", ",", "clear", "=", "False", ")", ":", "dc", "=", "daclConstants", "(", ")", "objectType", "=", "dc", ".", "getObjectTypeBit", "(", "objectType", ")", "path", "=", "dc", ".", "processPath", "(", ...
enable/disable inheritance on an object Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) clear: True will remove non-Inherited ACEs from the ACL Returns (dict): A dictionary containing the results CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.enable_inheritance c:\temp directory
[ "enable", "/", "disable", "inheritance", "on", "an", "object" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L653-L674
train
saltstack/salt
salt/modules/win_dacl.py
disable_inheritance
def disable_inheritance(path, objectType, copy=True): ''' Disable inheritance on an object Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) copy: True will copy the Inherited ACEs to the DACL before disabling inheritance Returns (dict): A dictionary containing the results CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.disable_inheritance c:\temp directory ''' dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectType) return _set_dacl_inheritance(path, objectType, False, copy, None)
python
def disable_inheritance(path, objectType, copy=True): ''' Disable inheritance on an object Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) copy: True will copy the Inherited ACEs to the DACL before disabling inheritance Returns (dict): A dictionary containing the results CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.disable_inheritance c:\temp directory ''' dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectType) return _set_dacl_inheritance(path, objectType, False, copy, None)
[ "def", "disable_inheritance", "(", "path", ",", "objectType", ",", "copy", "=", "True", ")", ":", "dc", "=", "daclConstants", "(", ")", "objectType", "=", "dc", ".", "getObjectTypeBit", "(", "objectType", ")", "path", "=", "dc", ".", "processPath", "(", ...
Disable inheritance on an object Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) copy: True will copy the Inherited ACEs to the DACL before disabling inheritance Returns (dict): A dictionary containing the results CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.disable_inheritance c:\temp directory
[ "Disable", "inheritance", "on", "an", "object" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L677-L698
train
saltstack/salt
salt/modules/win_dacl.py
check_inheritance
def check_inheritance(path, objectType, user=None): ''' Check a specified path to verify if inheritance is enabled Args: path: path of the registry key or file system object to check objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: if provided, will consider only the ACEs for that user Returns (bool): 'Inheritance' of True/False CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.check_inheritance c:\temp directory <username> ''' ret = {'result': False, 'Inheritance': False, 'comment': ''} sidRet = _getUserSid(user) dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectType) try: sd = win32security.GetNamedSecurityInfo(path, objectType, win32security.DACL_SECURITY_INFORMATION) dacls = sd.GetSecurityDescriptorDacl() except Exception as e: ret['result'] = False ret['comment'] = 'Error obtaining the Security Descriptor or DACL of the path: {0}.'.format(e) return ret for counter in range(0, dacls.GetAceCount()): ace = dacls.GetAce(counter) if (ace[0][1] & win32security.INHERITED_ACE) == win32security.INHERITED_ACE: if not sidRet['sid'] or ace[2] == sidRet['sid']: ret['Inheritance'] = True break ret['result'] = True return ret
python
def check_inheritance(path, objectType, user=None): ''' Check a specified path to verify if inheritance is enabled Args: path: path of the registry key or file system object to check objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: if provided, will consider only the ACEs for that user Returns (bool): 'Inheritance' of True/False CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.check_inheritance c:\temp directory <username> ''' ret = {'result': False, 'Inheritance': False, 'comment': ''} sidRet = _getUserSid(user) dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectType) try: sd = win32security.GetNamedSecurityInfo(path, objectType, win32security.DACL_SECURITY_INFORMATION) dacls = sd.GetSecurityDescriptorDacl() except Exception as e: ret['result'] = False ret['comment'] = 'Error obtaining the Security Descriptor or DACL of the path: {0}.'.format(e) return ret for counter in range(0, dacls.GetAceCount()): ace = dacls.GetAce(counter) if (ace[0][1] & win32security.INHERITED_ACE) == win32security.INHERITED_ACE: if not sidRet['sid'] or ace[2] == sidRet['sid']: ret['Inheritance'] = True break ret['result'] = True return ret
[ "def", "check_inheritance", "(", "path", ",", "objectType", ",", "user", "=", "None", ")", ":", "ret", "=", "{", "'result'", ":", "False", ",", "'Inheritance'", ":", "False", ",", "'comment'", ":", "''", "}", "sidRet", "=", "_getUserSid", "(", "user", ...
Check a specified path to verify if inheritance is enabled Args: path: path of the registry key or file system object to check objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: if provided, will consider only the ACEs for that user Returns (bool): 'Inheritance' of True/False CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.check_inheritance c:\temp directory <username>
[ "Check", "a", "specified", "path", "to", "verify", "if", "inheritance", "is", "enabled" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L701-L745
train
saltstack/salt
salt/modules/win_dacl.py
check_ace
def check_ace(path, objectType, user, permission=None, acetype=None, propagation=None, exactPermissionMatch=False): ''' Checks a path to verify the ACE (access control entry) specified exists Args: path: path to the file/reg key objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: user that the ACL is for permission: permission to test for (READ, FULLCONTROL, etc) acetype: the type of ACE (ALLOW or DENY) propagation: the propagation type of the ACE (FILES, FOLDERS, KEY, KEY&SUBKEYS, SUBKEYS, etc) exactPermissionMatch: the ACL must match exactly, IE if READ is specified, the user must have READ exactly and not FULLCONTROL (which also has the READ permission obviously) Returns (dict): 'Exists' true if the ACE exists, false if it does not CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.check_ace c:\temp directory <username> fullcontrol ''' ret = {'result': False, 'Exists': False, 'comment': ''} dc = daclConstants() objectTypeBit = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectTypeBit) permission = permission.upper() if permission else None acetype = acetype.upper() if permission else None propagation = propagation.upper() if propagation else None permissionbit = dc.getPermissionBit(objectTypeBit, permission) if permission else None acetypebit = dc.getAceTypeBit(acetype) if acetype else None propagationbit = dc.getPropagationBit(objectTypeBit, propagation) if propagation else None sidRet = _getUserSid(user) if not sidRet['result']: return sidRet dacls = _get_dacl(path, objectTypeBit) ret['result'] = True if dacls: for counter in range(0, dacls.GetAceCount()): ace = dacls.GetAce(counter) if ace[2] == sidRet['sid']: if not acetypebit or ace[0][0] == acetypebit: if not propagationbit or (ace[0][1] & propagationbit) == propagationbit: if not permissionbit: ret['Exists'] = True return ret if exactPermissionMatch: if ace[1] == permissionbit: ret['Exists'] = True return ret else: if (ace[1] & permissionbit) == permissionbit: ret['Exists'] = True return ret else: ret['comment'] = 'No DACL found for object.' return ret
python
def check_ace(path, objectType, user, permission=None, acetype=None, propagation=None, exactPermissionMatch=False): ''' Checks a path to verify the ACE (access control entry) specified exists Args: path: path to the file/reg key objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: user that the ACL is for permission: permission to test for (READ, FULLCONTROL, etc) acetype: the type of ACE (ALLOW or DENY) propagation: the propagation type of the ACE (FILES, FOLDERS, KEY, KEY&SUBKEYS, SUBKEYS, etc) exactPermissionMatch: the ACL must match exactly, IE if READ is specified, the user must have READ exactly and not FULLCONTROL (which also has the READ permission obviously) Returns (dict): 'Exists' true if the ACE exists, false if it does not CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.check_ace c:\temp directory <username> fullcontrol ''' ret = {'result': False, 'Exists': False, 'comment': ''} dc = daclConstants() objectTypeBit = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectTypeBit) permission = permission.upper() if permission else None acetype = acetype.upper() if permission else None propagation = propagation.upper() if propagation else None permissionbit = dc.getPermissionBit(objectTypeBit, permission) if permission else None acetypebit = dc.getAceTypeBit(acetype) if acetype else None propagationbit = dc.getPropagationBit(objectTypeBit, propagation) if propagation else None sidRet = _getUserSid(user) if not sidRet['result']: return sidRet dacls = _get_dacl(path, objectTypeBit) ret['result'] = True if dacls: for counter in range(0, dacls.GetAceCount()): ace = dacls.GetAce(counter) if ace[2] == sidRet['sid']: if not acetypebit or ace[0][0] == acetypebit: if not propagationbit or (ace[0][1] & propagationbit) == propagationbit: if not permissionbit: ret['Exists'] = True return ret if exactPermissionMatch: if ace[1] == permissionbit: ret['Exists'] = True return ret else: if (ace[1] & permissionbit) == permissionbit: ret['Exists'] = True return ret else: ret['comment'] = 'No DACL found for object.' return ret
[ "def", "check_ace", "(", "path", ",", "objectType", ",", "user", ",", "permission", "=", "None", ",", "acetype", "=", "None", ",", "propagation", "=", "None", ",", "exactPermissionMatch", "=", "False", ")", ":", "ret", "=", "{", "'result'", ":", "False",...
Checks a path to verify the ACE (access control entry) specified exists Args: path: path to the file/reg key objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: user that the ACL is for permission: permission to test for (READ, FULLCONTROL, etc) acetype: the type of ACE (ALLOW or DENY) propagation: the propagation type of the ACE (FILES, FOLDERS, KEY, KEY&SUBKEYS, SUBKEYS, etc) exactPermissionMatch: the ACL must match exactly, IE if READ is specified, the user must have READ exactly and not FULLCONTROL (which also has the READ permission obviously) Returns (dict): 'Exists' true if the ACE exists, false if it does not CLI Example: .. code-block:: bash salt 'minion-id' win_dacl.check_ace c:\temp directory <username> fullcontrol
[ "Checks", "a", "path", "to", "verify", "the", "ACE", "(", "access", "control", "entry", ")", "specified", "exists" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L748-L810
train
saltstack/salt
salt/modules/win_dacl.py
daclConstants.getObjectTypeBit
def getObjectTypeBit(self, t): ''' returns the bit value of the string object type ''' if isinstance(t, string_types): t = t.upper() try: return self.objectType[t] except KeyError: raise CommandExecutionError(( 'Invalid object type "{0}". It should be one of the following: {1}' ).format(t, ', '.join(self.objectType))) else: return t
python
def getObjectTypeBit(self, t): ''' returns the bit value of the string object type ''' if isinstance(t, string_types): t = t.upper() try: return self.objectType[t] except KeyError: raise CommandExecutionError(( 'Invalid object type "{0}". It should be one of the following: {1}' ).format(t, ', '.join(self.objectType))) else: return t
[ "def", "getObjectTypeBit", "(", "self", ",", "t", ")", ":", "if", "isinstance", "(", "t", ",", "string_types", ")", ":", "t", "=", "t", ".", "upper", "(", ")", "try", ":", "return", "self", ".", "objectType", "[", "t", "]", "except", "KeyError", ":...
returns the bit value of the string object type
[ "returns", "the", "bit", "value", "of", "the", "string", "object", "type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L193-L206
train
saltstack/salt
salt/modules/win_dacl.py
daclConstants.getSecurityHkey
def getSecurityHkey(self, s): ''' returns the necessary string value for an HKEY for the win32security module ''' try: return self.hkeys_security[s] except KeyError: raise CommandExecutionError(( 'No HKEY named "{0}". It should be one of the following: {1}' ).format(s, ', '.join(self.hkeys_security)))
python
def getSecurityHkey(self, s): ''' returns the necessary string value for an HKEY for the win32security module ''' try: return self.hkeys_security[s] except KeyError: raise CommandExecutionError(( 'No HKEY named "{0}". It should be one of the following: {1}' ).format(s, ', '.join(self.hkeys_security)))
[ "def", "getSecurityHkey", "(", "self", ",", "s", ")", ":", "try", ":", "return", "self", ".", "hkeys_security", "[", "s", "]", "except", "KeyError", ":", "raise", "CommandExecutionError", "(", "(", "'No HKEY named \"{0}\". It should be one of the following: {1}'", ...
returns the necessary string value for an HKEY for the win32security module
[ "returns", "the", "necessary", "string", "value", "for", "an", "HKEY", "for", "the", "win32security", "module" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L208-L217
train
saltstack/salt
salt/modules/win_dacl.py
daclConstants.getPermissionBit
def getPermissionBit(self, t, m): ''' returns a permission bit of the string permission value for the specified object type ''' try: if isinstance(m, string_types): return self.rights[t][m]['BITS'] else: return m except KeyError: raise CommandExecutionError(( 'No right "{0}". It should be one of the following: {1}') .format(m, ', '.join(self.rights[t])))
python
def getPermissionBit(self, t, m): ''' returns a permission bit of the string permission value for the specified object type ''' try: if isinstance(m, string_types): return self.rights[t][m]['BITS'] else: return m except KeyError: raise CommandExecutionError(( 'No right "{0}". It should be one of the following: {1}') .format(m, ', '.join(self.rights[t])))
[ "def", "getPermissionBit", "(", "self", ",", "t", ",", "m", ")", ":", "try", ":", "if", "isinstance", "(", "m", ",", "string_types", ")", ":", "return", "self", ".", "rights", "[", "t", "]", "[", "m", "]", "[", "'BITS'", "]", "else", ":", "return...
returns a permission bit of the string permission value for the specified object type
[ "returns", "a", "permission", "bit", "of", "the", "string", "permission", "value", "for", "the", "specified", "object", "type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L219-L231
train
saltstack/salt
salt/modules/win_dacl.py
daclConstants.getPermissionText
def getPermissionText(self, t, m): ''' returns the permission textual representation of a specified permission bit/object type ''' try: return self.rights[t][m]['TEXT'] except KeyError: raise CommandExecutionError(( 'No right "{0}". It should be one of the following: {1}') .format(m, ', '.join(self.rights[t])))
python
def getPermissionText(self, t, m): ''' returns the permission textual representation of a specified permission bit/object type ''' try: return self.rights[t][m]['TEXT'] except KeyError: raise CommandExecutionError(( 'No right "{0}". It should be one of the following: {1}') .format(m, ', '.join(self.rights[t])))
[ "def", "getPermissionText", "(", "self", ",", "t", ",", "m", ")", ":", "try", ":", "return", "self", ".", "rights", "[", "t", "]", "[", "m", "]", "[", "'TEXT'", "]", "except", "KeyError", ":", "raise", "CommandExecutionError", "(", "(", "'No right \"{0...
returns the permission textual representation of a specified permission bit/object type
[ "returns", "the", "permission", "textual", "representation", "of", "a", "specified", "permission", "bit", "/", "object", "type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L233-L242
train
saltstack/salt
salt/modules/win_dacl.py
daclConstants.getAceTypeBit
def getAceTypeBit(self, t): ''' returns the acetype bit of a text value ''' try: return self.validAceTypes[t]['BITS'] except KeyError: raise CommandExecutionError(( 'No ACE type "{0}". It should be one of the following: {1}' ).format(t, ', '.join(self.validAceTypes)))
python
def getAceTypeBit(self, t): ''' returns the acetype bit of a text value ''' try: return self.validAceTypes[t]['BITS'] except KeyError: raise CommandExecutionError(( 'No ACE type "{0}". It should be one of the following: {1}' ).format(t, ', '.join(self.validAceTypes)))
[ "def", "getAceTypeBit", "(", "self", ",", "t", ")", ":", "try", ":", "return", "self", ".", "validAceTypes", "[", "t", "]", "[", "'BITS'", "]", "except", "KeyError", ":", "raise", "CommandExecutionError", "(", "(", "'No ACE type \"{0}\". It should be one of the...
returns the acetype bit of a text value
[ "returns", "the", "acetype", "bit", "of", "a", "text", "value" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L244-L253
train
saltstack/salt
salt/modules/win_dacl.py
daclConstants.getAceTypeText
def getAceTypeText(self, t): ''' returns the textual representation of a acetype bit ''' try: return self.validAceTypes[t]['TEXT'] except KeyError: raise CommandExecutionError(( 'No ACE type "{0}". It should be one of the following: {1}' ).format(t, ', '.join(self.validAceTypes)))
python
def getAceTypeText(self, t): ''' returns the textual representation of a acetype bit ''' try: return self.validAceTypes[t]['TEXT'] except KeyError: raise CommandExecutionError(( 'No ACE type "{0}". It should be one of the following: {1}' ).format(t, ', '.join(self.validAceTypes)))
[ "def", "getAceTypeText", "(", "self", ",", "t", ")", ":", "try", ":", "return", "self", ".", "validAceTypes", "[", "t", "]", "[", "'TEXT'", "]", "except", "KeyError", ":", "raise", "CommandExecutionError", "(", "(", "'No ACE type \"{0}\". It should be one of th...
returns the textual representation of a acetype bit
[ "returns", "the", "textual", "representation", "of", "a", "acetype", "bit" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L255-L264
train
saltstack/salt
salt/modules/win_dacl.py
daclConstants.getPropagationBit
def getPropagationBit(self, t, p): ''' returns the propagation bit of a text value ''' try: return self.validPropagations[t][p]['BITS'] except KeyError: raise CommandExecutionError(( 'No propagation type of "{0}". It should be one of the following: {1}' ).format(p, ', '.join(self.validPropagations[t])))
python
def getPropagationBit(self, t, p): ''' returns the propagation bit of a text value ''' try: return self.validPropagations[t][p]['BITS'] except KeyError: raise CommandExecutionError(( 'No propagation type of "{0}". It should be one of the following: {1}' ).format(p, ', '.join(self.validPropagations[t])))
[ "def", "getPropagationBit", "(", "self", ",", "t", ",", "p", ")", ":", "try", ":", "return", "self", ".", "validPropagations", "[", "t", "]", "[", "p", "]", "[", "'BITS'", "]", "except", "KeyError", ":", "raise", "CommandExecutionError", "(", "(", "'No...
returns the propagation bit of a text value
[ "returns", "the", "propagation", "bit", "of", "a", "text", "value" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L266-L275
train
saltstack/salt
salt/modules/win_dacl.py
daclConstants.processPath
def processPath(self, path, objectType): ''' processes a path/object type combo and returns: registry types with the correct HKEY text representation files/directories with environment variables expanded ''' if objectType == win32security.SE_REGISTRY_KEY: splt = path.split("\\") hive = self.getSecurityHkey(splt.pop(0).upper()) splt.insert(0, hive) path = r'\\'.join(splt) else: path = os.path.expandvars(path) return path
python
def processPath(self, path, objectType): ''' processes a path/object type combo and returns: registry types with the correct HKEY text representation files/directories with environment variables expanded ''' if objectType == win32security.SE_REGISTRY_KEY: splt = path.split("\\") hive = self.getSecurityHkey(splt.pop(0).upper()) splt.insert(0, hive) path = r'\\'.join(splt) else: path = os.path.expandvars(path) return path
[ "def", "processPath", "(", "self", ",", "path", ",", "objectType", ")", ":", "if", "objectType", "==", "win32security", ".", "SE_REGISTRY_KEY", ":", "splt", "=", "path", ".", "split", "(", "\"\\\\\"", ")", "hive", "=", "self", ".", "getSecurityHkey", "(", ...
processes a path/object type combo and returns: registry types with the correct HKEY text representation files/directories with environment variables expanded
[ "processes", "a", "path", "/", "object", "type", "combo", "and", "returns", ":", "registry", "types", "with", "the", "correct", "HKEY", "text", "representation", "files", "/", "directories", "with", "environment", "variables", "expanded" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L288-L301
train
saltstack/salt
salt/states/neutron_subnet.py
present
def present(name, auth=None, **kwargs): ''' Ensure a subnet exists and is up-to-date name Name of the subnet network_name_or_id The unique name or ID of the attached network. If a non-unique name is supplied, an exception is raised. allocation_pools A list of dictionaries of the start and end addresses for the allocation pools gateway_ip The gateway IP address. dns_nameservers A list of DNS name servers for the subnet. host_routes A list of host route dictionaries for the subnet. ipv6_ra_mode IPv6 Router Advertisement mode. Valid values are: ‘dhcpv6-stateful’, ‘dhcpv6-stateless’, or ‘slaac’. ipv6_address_mode IPv6 address mode. Valid values are: ‘dhcpv6-stateful’, ‘dhcpv6-stateless’, or ‘slaac’. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} kwargs = __utils__['args.clean_kwargs'](**kwargs) __salt__['neutronng.setup_clouds'](auth) kwargs['subnet_name'] = name subnet = __salt__['neutronng.subnet_get'](name=name) if subnet is None: if __opts__['test']: ret['result'] = None ret['changes'] = kwargs ret['comment'] = 'Subnet will be created.' return ret new_subnet = __salt__['neutronng.subnet_create'](**kwargs) ret['changes'] = new_subnet ret['comment'] = 'Created subnet' return ret changes = __salt__['neutronng.compare_changes'](subnet, **kwargs) if changes: if __opts__['test'] is True: ret['result'] = None ret['changes'] = changes ret['comment'] = 'Project will be updated.' return ret # update_subnet does not support changing cidr, # so we have to delete and recreate the subnet in this case. if 'cidr' in changes or 'tenant_id' in changes: __salt__['neutronng.subnet_delete'](name=name) new_subnet = __salt__['neutronng.subnet_create'](**kwargs) ret['changes'] = new_subnet ret['comment'] = 'Deleted and recreated subnet' return ret __salt__['neutronng.subnet_update'](**kwargs) ret['changes'].update(changes) ret['comment'] = 'Updated subnet' return ret
python
def present(name, auth=None, **kwargs): ''' Ensure a subnet exists and is up-to-date name Name of the subnet network_name_or_id The unique name or ID of the attached network. If a non-unique name is supplied, an exception is raised. allocation_pools A list of dictionaries of the start and end addresses for the allocation pools gateway_ip The gateway IP address. dns_nameservers A list of DNS name servers for the subnet. host_routes A list of host route dictionaries for the subnet. ipv6_ra_mode IPv6 Router Advertisement mode. Valid values are: ‘dhcpv6-stateful’, ‘dhcpv6-stateless’, or ‘slaac’. ipv6_address_mode IPv6 address mode. Valid values are: ‘dhcpv6-stateful’, ‘dhcpv6-stateless’, or ‘slaac’. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} kwargs = __utils__['args.clean_kwargs'](**kwargs) __salt__['neutronng.setup_clouds'](auth) kwargs['subnet_name'] = name subnet = __salt__['neutronng.subnet_get'](name=name) if subnet is None: if __opts__['test']: ret['result'] = None ret['changes'] = kwargs ret['comment'] = 'Subnet will be created.' return ret new_subnet = __salt__['neutronng.subnet_create'](**kwargs) ret['changes'] = new_subnet ret['comment'] = 'Created subnet' return ret changes = __salt__['neutronng.compare_changes'](subnet, **kwargs) if changes: if __opts__['test'] is True: ret['result'] = None ret['changes'] = changes ret['comment'] = 'Project will be updated.' return ret # update_subnet does not support changing cidr, # so we have to delete and recreate the subnet in this case. if 'cidr' in changes or 'tenant_id' in changes: __salt__['neutronng.subnet_delete'](name=name) new_subnet = __salt__['neutronng.subnet_create'](**kwargs) ret['changes'] = new_subnet ret['comment'] = 'Deleted and recreated subnet' return ret __salt__['neutronng.subnet_update'](**kwargs) ret['changes'].update(changes) ret['comment'] = 'Updated subnet' return ret
[ "def", "present", "(", "name", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "kwargs", "=", ...
Ensure a subnet exists and is up-to-date name Name of the subnet network_name_or_id The unique name or ID of the attached network. If a non-unique name is supplied, an exception is raised. allocation_pools A list of dictionaries of the start and end addresses for the allocation pools gateway_ip The gateway IP address. dns_nameservers A list of DNS name servers for the subnet. host_routes A list of host route dictionaries for the subnet. ipv6_ra_mode IPv6 Router Advertisement mode. Valid values are: ‘dhcpv6-stateful’, ‘dhcpv6-stateless’, or ‘slaac’. ipv6_address_mode IPv6 address mode. Valid values are: ‘dhcpv6-stateful’, ‘dhcpv6-stateless’, or ‘slaac’.
[ "Ensure", "a", "subnet", "exists", "and", "is", "up", "-", "to", "-", "date" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/neutron_subnet.py#L62-L139
train
saltstack/salt
salt/states/neutron_subnet.py
absent
def absent(name, auth=None): ''' Ensure a subnet does not exists name Name of the subnet ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} __salt__['neutronng.setup_clouds'](auth) subnet = __salt__['neutronng.subnet_get'](name=name) if subnet: if __opts__['test'] is True: ret['result'] = None ret['changes'] = {'id': subnet.id} ret['comment'] = 'Project will be deleted.' return ret __salt__['neutronng.subnet_delete'](name=subnet) ret['changes']['id'] = name ret['comment'] = 'Deleted subnet' return ret
python
def absent(name, auth=None): ''' Ensure a subnet does not exists name Name of the subnet ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} __salt__['neutronng.setup_clouds'](auth) subnet = __salt__['neutronng.subnet_get'](name=name) if subnet: if __opts__['test'] is True: ret['result'] = None ret['changes'] = {'id': subnet.id} ret['comment'] = 'Project will be deleted.' return ret __salt__['neutronng.subnet_delete'](name=subnet) ret['changes']['id'] = name ret['comment'] = 'Deleted subnet' return ret
[ "def", "absent", "(", "name", ",", "auth", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "__salt__", "[", "'neutronng.setup_clouds'", "]...
Ensure a subnet does not exists name Name of the subnet
[ "Ensure", "a", "subnet", "does", "not", "exists" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/neutron_subnet.py#L142-L170
train
saltstack/salt
salt/runners/virt.py
_determine_host
def _determine_host(data, omit=''): ''' Determine what the most resource free host is based on the given data ''' # This is just checking for the host with the most free ram, this needs # to be much more complicated. host = '' bestmem = 0 for hv_, comps in six.iteritems(data): if hv_ == omit: continue if not isinstance(comps, dict): continue if comps.get('freemem', 0) > bestmem: bestmem = comps['freemem'] host = hv_ return host
python
def _determine_host(data, omit=''): ''' Determine what the most resource free host is based on the given data ''' # This is just checking for the host with the most free ram, this needs # to be much more complicated. host = '' bestmem = 0 for hv_, comps in six.iteritems(data): if hv_ == omit: continue if not isinstance(comps, dict): continue if comps.get('freemem', 0) > bestmem: bestmem = comps['freemem'] host = hv_ return host
[ "def", "_determine_host", "(", "data", ",", "omit", "=", "''", ")", ":", "# This is just checking for the host with the most free ram, this needs", "# to be much more complicated.", "host", "=", "''", "bestmem", "=", "0", "for", "hv_", ",", "comps", "in", "six", ".", ...
Determine what the most resource free host is based on the given data
[ "Determine", "what", "the", "most", "resource", "free", "host", "is", "based", "on", "the", "given", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L25-L41
train
saltstack/salt
salt/runners/virt.py
_find_vm
def _find_vm(name, data, quiet=False): ''' Scan the query data for the named VM ''' for hv_ in data: # Check if data is a dict, and not '"virt.full_info" is not available.' if not isinstance(data[hv_], dict): continue if name in data[hv_].get('vm_info', {}): ret = {hv_: {name: data[hv_]['vm_info'][name]}} if not quiet: __jid_event__.fire_event({'data': ret, 'outputter': 'nested'}, 'progress') return ret return {}
python
def _find_vm(name, data, quiet=False): ''' Scan the query data for the named VM ''' for hv_ in data: # Check if data is a dict, and not '"virt.full_info" is not available.' if not isinstance(data[hv_], dict): continue if name in data[hv_].get('vm_info', {}): ret = {hv_: {name: data[hv_]['vm_info'][name]}} if not quiet: __jid_event__.fire_event({'data': ret, 'outputter': 'nested'}, 'progress') return ret return {}
[ "def", "_find_vm", "(", "name", ",", "data", ",", "quiet", "=", "False", ")", ":", "for", "hv_", "in", "data", ":", "# Check if data is a dict, and not '\"virt.full_info\" is not available.'", "if", "not", "isinstance", "(", "data", "[", "hv_", "]", ",", "dict",...
Scan the query data for the named VM
[ "Scan", "the", "query", "data", "for", "the", "named", "VM" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L44-L57
train
saltstack/salt
salt/runners/virt.py
query
def query(host=None, quiet=False): ''' Query the virtual machines. When called without options all hosts are detected and a full query is returned. A single host can be passed in to specify an individual host to query. ''' if quiet: log.warning("'quiet' is deprecated. Please migrate to --quiet") ret = {} client = salt.client.get_local_client(__opts__['conf_file']) try: for info in client.cmd_iter('virtual:physical', 'virt.full_info', tgt_type='grain'): if not info: continue if not isinstance(info, dict): continue chunk = {} id_ = next(six.iterkeys(info)) if host: if host != id_: continue if not isinstance(info[id_], dict): continue if 'ret' not in info[id_]: continue if not isinstance(info[id_]['ret'], dict): continue chunk[id_] = info[id_]['ret'] ret.update(chunk) if not quiet: __jid_event__.fire_event({'data': chunk, 'outputter': 'virt_query'}, 'progress') except SaltClientError as client_error: print(client_error) return ret
python
def query(host=None, quiet=False): ''' Query the virtual machines. When called without options all hosts are detected and a full query is returned. A single host can be passed in to specify an individual host to query. ''' if quiet: log.warning("'quiet' is deprecated. Please migrate to --quiet") ret = {} client = salt.client.get_local_client(__opts__['conf_file']) try: for info in client.cmd_iter('virtual:physical', 'virt.full_info', tgt_type='grain'): if not info: continue if not isinstance(info, dict): continue chunk = {} id_ = next(six.iterkeys(info)) if host: if host != id_: continue if not isinstance(info[id_], dict): continue if 'ret' not in info[id_]: continue if not isinstance(info[id_]['ret'], dict): continue chunk[id_] = info[id_]['ret'] ret.update(chunk) if not quiet: __jid_event__.fire_event({'data': chunk, 'outputter': 'virt_query'}, 'progress') except SaltClientError as client_error: print(client_error) return ret
[ "def", "query", "(", "host", "=", "None", ",", "quiet", "=", "False", ")", ":", "if", "quiet", ":", "log", ".", "warning", "(", "\"'quiet' is deprecated. Please migrate to --quiet\"", ")", "ret", "=", "{", "}", "client", "=", "salt", ".", "client", ".", ...
Query the virtual machines. When called without options all hosts are detected and a full query is returned. A single host can be passed in to specify an individual host to query.
[ "Query", "the", "virtual", "machines", ".", "When", "called", "without", "options", "all", "hosts", "are", "detected", "and", "a", "full", "query", "is", "returned", ".", "A", "single", "host", "can", "be", "passed", "in", "to", "specify", "an", "individua...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L60-L94
train
saltstack/salt
salt/runners/virt.py
list
def list(host=None, quiet=False, hyper=None): # pylint: disable=redefined-builtin ''' List the virtual machines on each host, this is a simplified query, showing only the virtual machine names belonging to each host. A single host can be passed in to specify an individual host to list. ''' if quiet: log.warning("'quiet' is deprecated. Please migrate to --quiet") ret = {} client = salt.client.get_local_client(__opts__['conf_file']) for info in client.cmd_iter('virtual:physical', 'virt.vm_info', tgt_type='grain'): if not info: continue if not isinstance(info, dict): continue chunk = {} id_ = next(six.iterkeys(info)) if host: if host != id_: continue if not isinstance(info[id_], dict): continue if 'ret' not in info[id_]: continue if not isinstance(info[id_]['ret'], dict): continue data = {} for key, val in six.iteritems(info[id_]['ret']): if val['state'] in data: data[val['state']].append(key) else: data[val['state']] = [key] chunk[id_] = data ret.update(chunk) if not quiet: __jid_event__.fire_event({'data': chunk, 'outputter': 'nested'}, 'progress') return ret
python
def list(host=None, quiet=False, hyper=None): # pylint: disable=redefined-builtin ''' List the virtual machines on each host, this is a simplified query, showing only the virtual machine names belonging to each host. A single host can be passed in to specify an individual host to list. ''' if quiet: log.warning("'quiet' is deprecated. Please migrate to --quiet") ret = {} client = salt.client.get_local_client(__opts__['conf_file']) for info in client.cmd_iter('virtual:physical', 'virt.vm_info', tgt_type='grain'): if not info: continue if not isinstance(info, dict): continue chunk = {} id_ = next(six.iterkeys(info)) if host: if host != id_: continue if not isinstance(info[id_], dict): continue if 'ret' not in info[id_]: continue if not isinstance(info[id_]['ret'], dict): continue data = {} for key, val in six.iteritems(info[id_]['ret']): if val['state'] in data: data[val['state']].append(key) else: data[val['state']] = [key] chunk[id_] = data ret.update(chunk) if not quiet: __jid_event__.fire_event({'data': chunk, 'outputter': 'nested'}, 'progress') return ret
[ "def", "list", "(", "host", "=", "None", ",", "quiet", "=", "False", ",", "hyper", "=", "None", ")", ":", "# pylint: disable=redefined-builtin", "if", "quiet", ":", "log", ".", "warning", "(", "\"'quiet' is deprecated. Please migrate to --quiet\"", ")", "ret", "...
List the virtual machines on each host, this is a simplified query, showing only the virtual machine names belonging to each host. A single host can be passed in to specify an individual host to list.
[ "List", "the", "virtual", "machines", "on", "each", "host", "this", "is", "a", "simplified", "query", "showing", "only", "the", "virtual", "machine", "names", "belonging", "to", "each", "host", ".", "A", "single", "host", "can", "be", "passed", "in", "to",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L97-L136
train
saltstack/salt
salt/runners/virt.py
host_info
def host_info(host=None): ''' Return information about the host connected to this master ''' data = query(host, quiet=True) for id_ in data: if 'vm_info' in data[id_]: data[id_].pop('vm_info') __jid_event__.fire_event({'data': data, 'outputter': 'nested'}, 'progress') return data
python
def host_info(host=None): ''' Return information about the host connected to this master ''' data = query(host, quiet=True) for id_ in data: if 'vm_info' in data[id_]: data[id_].pop('vm_info') __jid_event__.fire_event({'data': data, 'outputter': 'nested'}, 'progress') return data
[ "def", "host_info", "(", "host", "=", "None", ")", ":", "data", "=", "query", "(", "host", ",", "quiet", "=", "True", ")", "for", "id_", "in", "data", ":", "if", "'vm_info'", "in", "data", "[", "id_", "]", ":", "data", "[", "id_", "]", ".", "po...
Return information about the host connected to this master
[ "Return", "information", "about", "the", "host", "connected", "to", "this", "master" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L150-L159
train
saltstack/salt
salt/runners/virt.py
init
def init( name, cpu, mem, image, hypervisor='kvm', host=None, seed=True, nic='default', install=True, start=True, disk='default', saltenv='base', enable_vnc=False, seed_cmd='seed.apply', enable_qcow=False, serial_type='None'): ''' This routine is used to create a new virtual machine. This routines takes a number of options to determine what the newly created virtual machine will look like. name The mandatory name of the new virtual machine. The name option is also the minion id, all minions must have an id. cpu The number of cpus to allocate to this new virtual machine. mem The amount of memory to allocate to this virtual machine. The number is interpreted in megabytes. image The network location of the virtual machine image, commonly a location on the salt fileserver, but http, https and ftp can also be used. hypervisor The hypervisor to use for the new virtual machine. Default is `kvm`. host The host to use for the new virtual machine, if this is omitted Salt will automatically detect what host to use. seed Set to `False` to prevent Salt from seeding the new virtual machine. nic The nic profile to use, defaults to the "default" nic profile which assumes a single network interface per VM associated with the "br0" bridge on the master. install Set to False to prevent Salt from installing a minion on the new VM before it spins up. disk The disk profile to use saltenv The Salt environment to use enable_vnc Whether a VNC screen is attached to resulting VM. Default is `False`. seed_cmd If seed is `True`, use this execution module function to seed new VM. Default is `seed.apply`. enable_qcow Clone disk image as a copy-on-write qcow2 image, using downloaded `image` as backing file. serial_type Enable serial console. Set to 'pty' for serial console or 'tcp' for telnet. Default is 'None' ''' __jid_event__.fire_event({'message': 'Searching for hosts'}, 'progress') data = query(host, quiet=True) # Check if the name is already deployed for node in data: if 'vm_info' in data[node]: if name in data[node]['vm_info']: __jid_event__.fire_event( {'message': 'Virtual machine {0} is already deployed'.format(name)}, 'progress' ) return 'fail' if host is None: host = _determine_host(data) if host not in data or not host: __jid_event__.fire_event( {'message': 'Host {0} was not found'.format(host)}, 'progress' ) return 'fail' pub_key = None priv_key = None if seed: __jid_event__.fire_event({'message': 'Minion will be preseeded'}, 'progress') priv_key, pub_key = salt.utils.cloud.gen_keys() accepted_key = os.path.join(__opts__['pki_dir'], 'minions', name) with salt.utils.files.fopen(accepted_key, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(pub_key)) client = salt.client.get_local_client(__opts__['conf_file']) __jid_event__.fire_event( {'message': 'Creating VM {0} on host {1}'.format(name, host)}, 'progress' ) try: cmd_ret = client.cmd_iter( host, 'virt.init', [ name, cpu, mem ], timeout=600, kwarg={ 'image': image, 'nic': nic, 'hypervisor': hypervisor, 'start': start, 'disk': disk, 'saltenv': saltenv, 'seed': seed, 'install': install, 'pub_key': pub_key, 'priv_key': priv_key, 'seed_cmd': seed_cmd, 'enable_vnc': enable_vnc, 'enable_qcow': enable_qcow, 'serial_type': serial_type, }) except SaltClientError as client_error: # Fall through to ret error handling below print(client_error) ret = next(cmd_ret) if not ret: __jid_event__.fire_event({'message': 'VM {0} was not initialized.'.format(name)}, 'progress') return 'fail' for minion_id in ret: if ret[minion_id]['ret'] is False: print('VM {0} initialization failed. Returned error: {1}'.format(name, ret[minion_id]['ret'])) return 'fail' __jid_event__.fire_event({'message': 'VM {0} initialized on host {1}'.format(name, host)}, 'progress') return 'good'
python
def init( name, cpu, mem, image, hypervisor='kvm', host=None, seed=True, nic='default', install=True, start=True, disk='default', saltenv='base', enable_vnc=False, seed_cmd='seed.apply', enable_qcow=False, serial_type='None'): ''' This routine is used to create a new virtual machine. This routines takes a number of options to determine what the newly created virtual machine will look like. name The mandatory name of the new virtual machine. The name option is also the minion id, all minions must have an id. cpu The number of cpus to allocate to this new virtual machine. mem The amount of memory to allocate to this virtual machine. The number is interpreted in megabytes. image The network location of the virtual machine image, commonly a location on the salt fileserver, but http, https and ftp can also be used. hypervisor The hypervisor to use for the new virtual machine. Default is `kvm`. host The host to use for the new virtual machine, if this is omitted Salt will automatically detect what host to use. seed Set to `False` to prevent Salt from seeding the new virtual machine. nic The nic profile to use, defaults to the "default" nic profile which assumes a single network interface per VM associated with the "br0" bridge on the master. install Set to False to prevent Salt from installing a minion on the new VM before it spins up. disk The disk profile to use saltenv The Salt environment to use enable_vnc Whether a VNC screen is attached to resulting VM. Default is `False`. seed_cmd If seed is `True`, use this execution module function to seed new VM. Default is `seed.apply`. enable_qcow Clone disk image as a copy-on-write qcow2 image, using downloaded `image` as backing file. serial_type Enable serial console. Set to 'pty' for serial console or 'tcp' for telnet. Default is 'None' ''' __jid_event__.fire_event({'message': 'Searching for hosts'}, 'progress') data = query(host, quiet=True) # Check if the name is already deployed for node in data: if 'vm_info' in data[node]: if name in data[node]['vm_info']: __jid_event__.fire_event( {'message': 'Virtual machine {0} is already deployed'.format(name)}, 'progress' ) return 'fail' if host is None: host = _determine_host(data) if host not in data or not host: __jid_event__.fire_event( {'message': 'Host {0} was not found'.format(host)}, 'progress' ) return 'fail' pub_key = None priv_key = None if seed: __jid_event__.fire_event({'message': 'Minion will be preseeded'}, 'progress') priv_key, pub_key = salt.utils.cloud.gen_keys() accepted_key = os.path.join(__opts__['pki_dir'], 'minions', name) with salt.utils.files.fopen(accepted_key, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(pub_key)) client = salt.client.get_local_client(__opts__['conf_file']) __jid_event__.fire_event( {'message': 'Creating VM {0} on host {1}'.format(name, host)}, 'progress' ) try: cmd_ret = client.cmd_iter( host, 'virt.init', [ name, cpu, mem ], timeout=600, kwarg={ 'image': image, 'nic': nic, 'hypervisor': hypervisor, 'start': start, 'disk': disk, 'saltenv': saltenv, 'seed': seed, 'install': install, 'pub_key': pub_key, 'priv_key': priv_key, 'seed_cmd': seed_cmd, 'enable_vnc': enable_vnc, 'enable_qcow': enable_qcow, 'serial_type': serial_type, }) except SaltClientError as client_error: # Fall through to ret error handling below print(client_error) ret = next(cmd_ret) if not ret: __jid_event__.fire_event({'message': 'VM {0} was not initialized.'.format(name)}, 'progress') return 'fail' for minion_id in ret: if ret[minion_id]['ret'] is False: print('VM {0} initialization failed. Returned error: {1}'.format(name, ret[minion_id]['ret'])) return 'fail' __jid_event__.fire_event({'message': 'VM {0} initialized on host {1}'.format(name, host)}, 'progress') return 'good'
[ "def", "init", "(", "name", ",", "cpu", ",", "mem", ",", "image", ",", "hypervisor", "=", "'kvm'", ",", "host", "=", "None", ",", "seed", "=", "True", ",", "nic", "=", "'default'", ",", "install", "=", "True", ",", "start", "=", "True", ",", "dis...
This routine is used to create a new virtual machine. This routines takes a number of options to determine what the newly created virtual machine will look like. name The mandatory name of the new virtual machine. The name option is also the minion id, all minions must have an id. cpu The number of cpus to allocate to this new virtual machine. mem The amount of memory to allocate to this virtual machine. The number is interpreted in megabytes. image The network location of the virtual machine image, commonly a location on the salt fileserver, but http, https and ftp can also be used. hypervisor The hypervisor to use for the new virtual machine. Default is `kvm`. host The host to use for the new virtual machine, if this is omitted Salt will automatically detect what host to use. seed Set to `False` to prevent Salt from seeding the new virtual machine. nic The nic profile to use, defaults to the "default" nic profile which assumes a single network interface per VM associated with the "br0" bridge on the master. install Set to False to prevent Salt from installing a minion on the new VM before it spins up. disk The disk profile to use saltenv The Salt environment to use enable_vnc Whether a VNC screen is attached to resulting VM. Default is `False`. seed_cmd If seed is `True`, use this execution module function to seed new VM. Default is `seed.apply`. enable_qcow Clone disk image as a copy-on-write qcow2 image, using downloaded `image` as backing file. serial_type Enable serial console. Set to 'pty' for serial console or 'tcp' for telnet. Default is 'None'
[ "This", "routine", "is", "used", "to", "create", "a", "new", "virtual", "machine", ".", "This", "routines", "takes", "a", "number", "of", "options", "to", "determine", "what", "the", "newly", "created", "virtual", "machine", "will", "look", "like", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L162-L317
train
saltstack/salt
salt/runners/virt.py
vm_info
def vm_info(name, quiet=False): ''' Return the information on the named VM ''' data = query(quiet=True) return _find_vm(name, data, quiet)
python
def vm_info(name, quiet=False): ''' Return the information on the named VM ''' data = query(quiet=True) return _find_vm(name, data, quiet)
[ "def", "vm_info", "(", "name", ",", "quiet", "=", "False", ")", ":", "data", "=", "query", "(", "quiet", "=", "True", ")", "return", "_find_vm", "(", "name", ",", "data", ",", "quiet", ")" ]
Return the information on the named VM
[ "Return", "the", "information", "on", "the", "named", "VM" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L320-L325
train
saltstack/salt
salt/runners/virt.py
reset
def reset(name): ''' Force power down and restart an existing VM ''' ret = {} client = salt.client.get_local_client(__opts__['conf_file']) data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event({'message': 'Failed to find VM {0} to reset'.format(name)}, 'progress') return 'fail' host = next(six.iterkeys(data)) try: cmd_ret = client.cmd_iter( host, 'virt.reset', [name], timeout=600) for comp in cmd_ret: ret.update(comp) __jid_event__.fire_event({'message': 'Reset VM {0}'.format(name)}, 'progress') except SaltClientError as client_error: print(client_error) return ret
python
def reset(name): ''' Force power down and restart an existing VM ''' ret = {} client = salt.client.get_local_client(__opts__['conf_file']) data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event({'message': 'Failed to find VM {0} to reset'.format(name)}, 'progress') return 'fail' host = next(six.iterkeys(data)) try: cmd_ret = client.cmd_iter( host, 'virt.reset', [name], timeout=600) for comp in cmd_ret: ret.update(comp) __jid_event__.fire_event({'message': 'Reset VM {0}'.format(name)}, 'progress') except SaltClientError as client_error: print(client_error) return ret
[ "def", "reset", "(", "name", ")", ":", "ret", "=", "{", "}", "client", "=", "salt", ".", "client", ".", "get_local_client", "(", "__opts__", "[", "'conf_file'", "]", ")", "data", "=", "vm_info", "(", "name", ",", "quiet", "=", "True", ")", "if", "n...
Force power down and restart an existing VM
[ "Force", "power", "down", "and", "restart", "an", "existing", "VM" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L328-L350
train
saltstack/salt
salt/runners/virt.py
purge
def purge(name, delete_key=True): ''' Destroy the named VM ''' ret = {} client = salt.client.get_local_client(__opts__['conf_file']) data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event({'error': 'Failed to find VM {0} to purge'.format(name)}, 'progress') return 'fail' host = next(six.iterkeys(data)) try: cmd_ret = client.cmd_iter( host, 'virt.purge', [name, True], timeout=600) except SaltClientError as client_error: return 'Virtual machine {0} could not be purged: {1}'.format(name, client_error) for comp in cmd_ret: ret.update(comp) if delete_key: log.debug('Deleting key %s', name) skey = salt.key.Key(__opts__) skey.delete_key(name) __jid_event__.fire_event({'message': 'Purged VM {0}'.format(name)}, 'progress') return 'good'
python
def purge(name, delete_key=True): ''' Destroy the named VM ''' ret = {} client = salt.client.get_local_client(__opts__['conf_file']) data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event({'error': 'Failed to find VM {0} to purge'.format(name)}, 'progress') return 'fail' host = next(six.iterkeys(data)) try: cmd_ret = client.cmd_iter( host, 'virt.purge', [name, True], timeout=600) except SaltClientError as client_error: return 'Virtual machine {0} could not be purged: {1}'.format(name, client_error) for comp in cmd_ret: ret.update(comp) if delete_key: log.debug('Deleting key %s', name) skey = salt.key.Key(__opts__) skey.delete_key(name) __jid_event__.fire_event({'message': 'Purged VM {0}'.format(name)}, 'progress') return 'good'
[ "def", "purge", "(", "name", ",", "delete_key", "=", "True", ")", ":", "ret", "=", "{", "}", "client", "=", "salt", ".", "client", ".", "get_local_client", "(", "__opts__", "[", "'conf_file'", "]", ")", "data", "=", "vm_info", "(", "name", ",", "quie...
Destroy the named VM
[ "Destroy", "the", "named", "VM" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L409-L437
train
saltstack/salt
salt/runners/virt.py
migrate
def migrate(name, target=''): ''' Migrate a VM from one host to another. This routine will just start the migration and display information on how to look up the progress. ''' client = salt.client.get_local_client(__opts__['conf_file']) data = query(quiet=True) origin_data = _find_vm(name, data, quiet=True) try: origin_host = list(origin_data.keys())[0] except IndexError: __jid_event__.fire_event({'error': 'Named VM {0} was not found to migrate'.format(name)}, 'progress') return '' disks = origin_data[origin_host][name]['disks'] if not origin_data: __jid_event__.fire_event({'error': 'Named VM {0} was not found to migrate'.format(name)}, 'progress') return '' if not target: target = _determine_host(data, origin_host) if target not in data: __jid_event__.fire_event({'error': 'Target host {0} not found'.format(origin_data)}, 'progress') return '' try: client.cmd(target, 'virt.seed_non_shared_migrate', [disks, True]) jid = client.cmd_async(origin_host, 'virt.migrate_non_shared', [name, target]) except SaltClientError as client_error: return 'Virtual machine {0} could not be migrated: {1}'.format(name, client_error) msg = ('The migration of virtual machine {0} to host {1} has begun, ' 'and can be tracked via jid {2}. The ``salt-run virt.query`` ' 'runner can also be used, the target VM will be shown as paused ' 'until the migration is complete.').format(name, target, jid) __jid_event__.fire_event({'message': msg}, 'progress')
python
def migrate(name, target=''): ''' Migrate a VM from one host to another. This routine will just start the migration and display information on how to look up the progress. ''' client = salt.client.get_local_client(__opts__['conf_file']) data = query(quiet=True) origin_data = _find_vm(name, data, quiet=True) try: origin_host = list(origin_data.keys())[0] except IndexError: __jid_event__.fire_event({'error': 'Named VM {0} was not found to migrate'.format(name)}, 'progress') return '' disks = origin_data[origin_host][name]['disks'] if not origin_data: __jid_event__.fire_event({'error': 'Named VM {0} was not found to migrate'.format(name)}, 'progress') return '' if not target: target = _determine_host(data, origin_host) if target not in data: __jid_event__.fire_event({'error': 'Target host {0} not found'.format(origin_data)}, 'progress') return '' try: client.cmd(target, 'virt.seed_non_shared_migrate', [disks, True]) jid = client.cmd_async(origin_host, 'virt.migrate_non_shared', [name, target]) except SaltClientError as client_error: return 'Virtual machine {0} could not be migrated: {1}'.format(name, client_error) msg = ('The migration of virtual machine {0} to host {1} has begun, ' 'and can be tracked via jid {2}. The ``salt-run virt.query`` ' 'runner can also be used, the target VM will be shown as paused ' 'until the migration is complete.').format(name, target, jid) __jid_event__.fire_event({'message': msg}, 'progress')
[ "def", "migrate", "(", "name", ",", "target", "=", "''", ")", ":", "client", "=", "salt", ".", "client", ".", "get_local_client", "(", "__opts__", "[", "'conf_file'", "]", ")", "data", "=", "query", "(", "quiet", "=", "True", ")", "origin_data", "=", ...
Migrate a VM from one host to another. This routine will just start the migration and display information on how to look up the progress.
[ "Migrate", "a", "VM", "from", "one", "host", "to", "another", ".", "This", "routine", "will", "just", "start", "the", "migration", "and", "display", "information", "on", "how", "to", "look", "up", "the", "progress", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/virt.py#L497-L531
train