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/renderers/aws_kms.py
_plaintext_data_key
def _plaintext_data_key(): ''' Return the configured KMS data key decrypted and encoded in urlsafe base64. Cache the result to minimize API calls to AWS. ''' response = getattr(_plaintext_data_key, 'response', None) cache_hit = response is not None if not cache_hit: response = _api_decrypt() setattr(_plaintext_data_key, 'response', response) key_id = response['KeyId'] plaintext = response['Plaintext'] if hasattr(plaintext, 'encode'): plaintext = plaintext.encode(__salt_system_encoding__) log.debug('Using key %s from %s', key_id, 'cache' if cache_hit else 'api call') return plaintext
python
def _plaintext_data_key(): ''' Return the configured KMS data key decrypted and encoded in urlsafe base64. Cache the result to minimize API calls to AWS. ''' response = getattr(_plaintext_data_key, 'response', None) cache_hit = response is not None if not cache_hit: response = _api_decrypt() setattr(_plaintext_data_key, 'response', response) key_id = response['KeyId'] plaintext = response['Plaintext'] if hasattr(plaintext, 'encode'): plaintext = plaintext.encode(__salt_system_encoding__) log.debug('Using key %s from %s', key_id, 'cache' if cache_hit else 'api call') return plaintext
[ "def", "_plaintext_data_key", "(", ")", ":", "response", "=", "getattr", "(", "_plaintext_data_key", ",", "'response'", ",", "None", ")", "cache_hit", "=", "response", "is", "not", "None", "if", "not", "cache_hit", ":", "response", "=", "_api_decrypt", "(", ...
Return the configured KMS data key decrypted and encoded in urlsafe base64. Cache the result to minimize API calls to AWS.
[ "Return", "the", "configured", "KMS", "data", "key", "decrypted", "and", "encoded", "in", "urlsafe", "base64", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/aws_kms.py#L179-L195
train
saltstack/salt
salt/renderers/aws_kms.py
_decrypt_ciphertext
def _decrypt_ciphertext(cipher, translate_newlines=False): ''' Given a blob of ciphertext as a bytestring, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out. ''' if translate_newlines: cipher = cipher.replace(r'\n', '\n') if hasattr(cipher, 'encode'): cipher = cipher.encode(__salt_system_encoding__) # Decryption data_key = _base64_plaintext_data_key() plain_text = fernet.Fernet(data_key).decrypt(cipher) if hasattr(plain_text, 'decode'): plain_text = plain_text.decode(__salt_system_encoding__) return six.text_type(plain_text)
python
def _decrypt_ciphertext(cipher, translate_newlines=False): ''' Given a blob of ciphertext as a bytestring, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out. ''' if translate_newlines: cipher = cipher.replace(r'\n', '\n') if hasattr(cipher, 'encode'): cipher = cipher.encode(__salt_system_encoding__) # Decryption data_key = _base64_plaintext_data_key() plain_text = fernet.Fernet(data_key).decrypt(cipher) if hasattr(plain_text, 'decode'): plain_text = plain_text.decode(__salt_system_encoding__) return six.text_type(plain_text)
[ "def", "_decrypt_ciphertext", "(", "cipher", ",", "translate_newlines", "=", "False", ")", ":", "if", "translate_newlines", ":", "cipher", "=", "cipher", ".", "replace", "(", "r'\\n'", ",", "'\\n'", ")", "if", "hasattr", "(", "cipher", ",", "'encode'", ")", ...
Given a blob of ciphertext as a bytestring, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out.
[ "Given", "a", "blob", "of", "ciphertext", "as", "a", "bytestring", "try", "to", "decrypt", "the", "cipher", "and", "return", "the", "decrypted", "string", ".", "If", "the", "cipher", "cannot", "be", "decrypted", "log", "the", "error", "and", "return", "the...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/aws_kms.py#L206-L222
train
saltstack/salt
salt/renderers/aws_kms.py
_decrypt_object
def _decrypt_object(obj, translate_newlines=False): ''' Recursively try to decrypt any object. Recur on objects that are not strings. Decrypt strings that are valid Fernet tokens. Return the rest unchanged. ''' if salt.utils.stringio.is_readable(obj): return _decrypt_object(obj.getvalue(), translate_newlines) if isinstance(obj, six.string_types): try: return _decrypt_ciphertext(obj, translate_newlines=translate_newlines) except (fernet.InvalidToken, TypeError): return obj elif isinstance(obj, dict): for key, value in six.iteritems(obj): obj[key] = _decrypt_object(value, translate_newlines=translate_newlines) return obj elif isinstance(obj, list): for key, value in enumerate(obj): obj[key] = _decrypt_object(value, translate_newlines=translate_newlines) return obj else: return obj
python
def _decrypt_object(obj, translate_newlines=False): ''' Recursively try to decrypt any object. Recur on objects that are not strings. Decrypt strings that are valid Fernet tokens. Return the rest unchanged. ''' if salt.utils.stringio.is_readable(obj): return _decrypt_object(obj.getvalue(), translate_newlines) if isinstance(obj, six.string_types): try: return _decrypt_ciphertext(obj, translate_newlines=translate_newlines) except (fernet.InvalidToken, TypeError): return obj elif isinstance(obj, dict): for key, value in six.iteritems(obj): obj[key] = _decrypt_object(value, translate_newlines=translate_newlines) return obj elif isinstance(obj, list): for key, value in enumerate(obj): obj[key] = _decrypt_object(value, translate_newlines=translate_newlines) return obj else: return obj
[ "def", "_decrypt_object", "(", "obj", ",", "translate_newlines", "=", "False", ")", ":", "if", "salt", ".", "utils", ".", "stringio", ".", "is_readable", "(", "obj", ")", ":", "return", "_decrypt_object", "(", "obj", ".", "getvalue", "(", ")", ",", "tran...
Recursively try to decrypt any object. Recur on objects that are not strings. Decrypt strings that are valid Fernet tokens. Return the rest unchanged.
[ "Recursively", "try", "to", "decrypt", "any", "object", ".", "Recur", "on", "objects", "that", "are", "not", "strings", ".", "Decrypt", "strings", "that", "are", "valid", "Fernet", "tokens", ".", "Return", "the", "rest", "unchanged", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/aws_kms.py#L225-L252
train
saltstack/salt
salt/renderers/aws_kms.py
render
def render(data, saltenv='base', sls='', argline='', **kwargs): # pylint: disable=unused-argument ''' Decrypt the data to be rendered that was encrypted using AWS KMS envelope encryption. ''' translate_newlines = kwargs.get('translate_newlines', False) return _decrypt_object(data, translate_newlines=translate_newlines)
python
def render(data, saltenv='base', sls='', argline='', **kwargs): # pylint: disable=unused-argument ''' Decrypt the data to be rendered that was encrypted using AWS KMS envelope encryption. ''' translate_newlines = kwargs.get('translate_newlines', False) return _decrypt_object(data, translate_newlines=translate_newlines)
[ "def", "render", "(", "data", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "argline", "=", "''", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "translate_newlines", "=", "kwargs", ".", "get", "(", "'translate_newlines'...
Decrypt the data to be rendered that was encrypted using AWS KMS envelope encryption.
[ "Decrypt", "the", "data", "to", "be", "rendered", "that", "was", "encrypted", "using", "AWS", "KMS", "envelope", "encryption", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/aws_kms.py#L255-L260
train
saltstack/salt
salt/modules/grains.py
_serial_sanitizer
def _serial_sanitizer(instr): '''Replaces the last 1/4 of a string with X's''' length = len(instr) index = int(math.floor(length * .75)) return '{0}{1}'.format(instr[:index], 'X' * (length - index))
python
def _serial_sanitizer(instr): '''Replaces the last 1/4 of a string with X's''' length = len(instr) index = int(math.floor(length * .75)) return '{0}{1}'.format(instr[:index], 'X' * (length - index))
[ "def", "_serial_sanitizer", "(", "instr", ")", ":", "length", "=", "len", "(", "instr", ")", "index", "=", "int", "(", "math", ".", "floor", "(", "length", "*", ".75", ")", ")", "return", "'{0}{1}'", ".", "format", "(", "instr", "[", ":", "index", ...
Replaces the last 1/4 of a string with X's
[ "Replaces", "the", "last", "1", "/", "4", "of", "a", "string", "with", "X", "s" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L55-L59
train
saltstack/salt
salt/modules/grains.py
get
def get(key, default='', delimiter=DEFAULT_TARGET_DELIM, ordered=True): ''' Attempt to retrieve the named value from grains, if the named value is not available return the passed default. The default return is an empty string. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in grains looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the apache key in the pkg dict this key can be passed:: pkg:apache :param delimiter: Specify an alternate delimiter to use when traversing a nested dict. This is useful for when the desired key contains a colon. See CLI example below for usage. .. versionadded:: 2014.7.0 :param ordered: Outputs an ordered dict if applicable (default: True) .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' grains.get pkg:apache salt '*' grains.get abc::def|ghi delimiter='|' ''' if ordered is True: grains = __grains__ else: grains = salt.utils.json.loads(salt.utils.json.dumps(__grains__)) return salt.utils.data.traverse_dict_and_list( grains, key, default, delimiter)
python
def get(key, default='', delimiter=DEFAULT_TARGET_DELIM, ordered=True): ''' Attempt to retrieve the named value from grains, if the named value is not available return the passed default. The default return is an empty string. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in grains looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the apache key in the pkg dict this key can be passed:: pkg:apache :param delimiter: Specify an alternate delimiter to use when traversing a nested dict. This is useful for when the desired key contains a colon. See CLI example below for usage. .. versionadded:: 2014.7.0 :param ordered: Outputs an ordered dict if applicable (default: True) .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' grains.get pkg:apache salt '*' grains.get abc::def|ghi delimiter='|' ''' if ordered is True: grains = __grains__ else: grains = salt.utils.json.loads(salt.utils.json.dumps(__grains__)) return salt.utils.data.traverse_dict_and_list( grains, key, default, delimiter)
[ "def", "get", "(", "key", ",", "default", "=", "''", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered", "=", "True", ")", ":", "if", "ordered", "is", "True", ":", "grains", "=", "__grains__", "else", ":", "grains", "=", "salt", ".", "utils"...
Attempt to retrieve the named value from grains, if the named value is not available return the passed default. The default return is an empty string. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in grains looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the apache key in the pkg dict this key can be passed:: pkg:apache :param delimiter: Specify an alternate delimiter to use when traversing a nested dict. This is useful for when the desired key contains a colon. See CLI example below for usage. .. versionadded:: 2014.7.0 :param ordered: Outputs an ordered dict if applicable (default: True) .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' grains.get pkg:apache salt '*' grains.get abc::def|ghi delimiter='|'
[ "Attempt", "to", "retrieve", "the", "named", "value", "from", "grains", "if", "the", "named", "value", "is", "not", "available", "return", "the", "passed", "default", ".", "The", "default", "return", "is", "an", "empty", "string", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L80-L123
train
saltstack/salt
salt/modules/grains.py
has_value
def has_value(key): ''' Determine whether a key exists in the grains dictionary. Given a grains dictionary that contains the following structure:: {'pkg': {'apache': 'httpd'}} One would determine if the apache key in the pkg dict exists by:: pkg:apache CLI Example: .. code-block:: bash salt '*' grains.has_value pkg:apache ''' return salt.utils.data.traverse_dict_and_list( __grains__, key, KeyError) is not KeyError
python
def has_value(key): ''' Determine whether a key exists in the grains dictionary. Given a grains dictionary that contains the following structure:: {'pkg': {'apache': 'httpd'}} One would determine if the apache key in the pkg dict exists by:: pkg:apache CLI Example: .. code-block:: bash salt '*' grains.has_value pkg:apache ''' return salt.utils.data.traverse_dict_and_list( __grains__, key, KeyError) is not KeyError
[ "def", "has_value", "(", "key", ")", ":", "return", "salt", ".", "utils", ".", "data", ".", "traverse_dict_and_list", "(", "__grains__", ",", "key", ",", "KeyError", ")", "is", "not", "KeyError" ]
Determine whether a key exists in the grains dictionary. Given a grains dictionary that contains the following structure:: {'pkg': {'apache': 'httpd'}} One would determine if the apache key in the pkg dict exists by:: pkg:apache CLI Example: .. code-block:: bash salt '*' grains.has_value pkg:apache
[ "Determine", "whether", "a", "key", "exists", "in", "the", "grains", "dictionary", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L126-L147
train
saltstack/salt
salt/modules/grains.py
items
def items(sanitize=False): ''' Return all of the minion's grains CLI Example: .. code-block:: bash salt '*' grains.items Sanitized CLI Example: .. code-block:: bash salt '*' grains.items sanitize=True ''' if salt.utils.data.is_true(sanitize): out = dict(__grains__) for key, func in six.iteritems(_SANITIZERS): if key in out: out[key] = func(out[key]) return out else: return __grains__
python
def items(sanitize=False): ''' Return all of the minion's grains CLI Example: .. code-block:: bash salt '*' grains.items Sanitized CLI Example: .. code-block:: bash salt '*' grains.items sanitize=True ''' if salt.utils.data.is_true(sanitize): out = dict(__grains__) for key, func in six.iteritems(_SANITIZERS): if key in out: out[key] = func(out[key]) return out else: return __grains__
[ "def", "items", "(", "sanitize", "=", "False", ")", ":", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "sanitize", ")", ":", "out", "=", "dict", "(", "__grains__", ")", "for", "key", ",", "func", "in", "six", ".", "iteritems", "(", ...
Return all of the minion's grains CLI Example: .. code-block:: bash salt '*' grains.items Sanitized CLI Example: .. code-block:: bash salt '*' grains.items sanitize=True
[ "Return", "all", "of", "the", "minion", "s", "grains" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L150-L173
train
saltstack/salt
salt/modules/grains.py
item
def item(*args, **kwargs): ''' Return one or more grains CLI Example: .. code-block:: bash salt '*' grains.item os salt '*' grains.item os osrelease oscodename Sanitized CLI Example: .. code-block:: bash salt '*' grains.item host sanitize=True ''' ret = {} default = kwargs.get('default', '') delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM) try: for arg in args: ret[arg] = salt.utils.data.traverse_dict_and_list( __grains__, arg, default, delimiter) except KeyError: pass if salt.utils.data.is_true(kwargs.get('sanitize')): for arg, func in six.iteritems(_SANITIZERS): if arg in ret: ret[arg] = func(ret[arg]) return ret
python
def item(*args, **kwargs): ''' Return one or more grains CLI Example: .. code-block:: bash salt '*' grains.item os salt '*' grains.item os osrelease oscodename Sanitized CLI Example: .. code-block:: bash salt '*' grains.item host sanitize=True ''' ret = {} default = kwargs.get('default', '') delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM) try: for arg in args: ret[arg] = salt.utils.data.traverse_dict_and_list( __grains__, arg, default, delimiter) except KeyError: pass if salt.utils.data.is_true(kwargs.get('sanitize')): for arg, func in six.iteritems(_SANITIZERS): if arg in ret: ret[arg] = func(ret[arg]) return ret
[ "def", "item", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "default", "=", "kwargs", ".", "get", "(", "'default'", ",", "''", ")", "delimiter", "=", "kwargs", ".", "get", "(", "'delimiter'", ",", "DEFAULT_TARGET_DELIM",...
Return one or more grains CLI Example: .. code-block:: bash salt '*' grains.item os salt '*' grains.item os osrelease oscodename Sanitized CLI Example: .. code-block:: bash salt '*' grains.item host sanitize=True
[ "Return", "one", "or", "more", "grains" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L176-L211
train
saltstack/salt
salt/modules/grains.py
setvals
def setvals(grains, destructive=False): ''' Set new grains values in the grains config file destructive If an operation results in a key being removed, delete the key, too. Defaults to False. CLI Example: .. code-block:: bash salt '*' grains.setvals "{'key1': 'val1', 'key2': 'val2'}" ''' new_grains = grains if not isinstance(new_grains, collections.Mapping): raise SaltException('setvals grains must be a dictionary.') grains = {} if os.path.isfile(__opts__['conf_file']): if salt.utils.platform.is_proxy(): gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'proxy.d', __opts__['id'], 'grains' ) else: gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'grains' ) elif os.path.isdir(__opts__['conf_file']): if salt.utils.platform.is_proxy(): gfn = os.path.join( __opts__['conf_file'], 'proxy.d', __opts__['id'], 'grains' ) else: gfn = os.path.join( __opts__['conf_file'], 'grains' ) else: if salt.utils.platform.is_proxy(): gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'proxy.d', __opts__['id'], 'grains' ) else: gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'grains' ) if os.path.isfile(gfn): with salt.utils.files.fopen(gfn, 'rb') as fp_: try: grains = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: return 'Unable to read existing grains file: {0}'.format(exc) if not isinstance(grains, dict): grains = {} for key, val in six.iteritems(new_grains): if val is None and destructive is True: if key in grains: del grains[key] if key in __grains__: del __grains__[key] else: grains[key] = val __grains__[key] = val try: with salt.utils.files.fopen(gfn, 'w+') as fp_: salt.utils.yaml.safe_dump(grains, fp_, default_flow_style=False) except (IOError, OSError): log.error( 'Unable to write to grains file at %s. Check permissions.', gfn ) fn_ = os.path.join(__opts__['cachedir'], 'module_refresh') try: with salt.utils.files.flopen(fn_, 'w+'): pass except (IOError, OSError): log.error( 'Unable to write to cache file %s. Check permissions.', fn_ ) if not __opts__.get('local', False): # Refresh the grains __salt__['saltutil.refresh_grains']() # Return the grains we just set to confirm everything was OK return new_grains
python
def setvals(grains, destructive=False): ''' Set new grains values in the grains config file destructive If an operation results in a key being removed, delete the key, too. Defaults to False. CLI Example: .. code-block:: bash salt '*' grains.setvals "{'key1': 'val1', 'key2': 'val2'}" ''' new_grains = grains if not isinstance(new_grains, collections.Mapping): raise SaltException('setvals grains must be a dictionary.') grains = {} if os.path.isfile(__opts__['conf_file']): if salt.utils.platform.is_proxy(): gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'proxy.d', __opts__['id'], 'grains' ) else: gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'grains' ) elif os.path.isdir(__opts__['conf_file']): if salt.utils.platform.is_proxy(): gfn = os.path.join( __opts__['conf_file'], 'proxy.d', __opts__['id'], 'grains' ) else: gfn = os.path.join( __opts__['conf_file'], 'grains' ) else: if salt.utils.platform.is_proxy(): gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'proxy.d', __opts__['id'], 'grains' ) else: gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'grains' ) if os.path.isfile(gfn): with salt.utils.files.fopen(gfn, 'rb') as fp_: try: grains = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: return 'Unable to read existing grains file: {0}'.format(exc) if not isinstance(grains, dict): grains = {} for key, val in six.iteritems(new_grains): if val is None and destructive is True: if key in grains: del grains[key] if key in __grains__: del __grains__[key] else: grains[key] = val __grains__[key] = val try: with salt.utils.files.fopen(gfn, 'w+') as fp_: salt.utils.yaml.safe_dump(grains, fp_, default_flow_style=False) except (IOError, OSError): log.error( 'Unable to write to grains file at %s. Check permissions.', gfn ) fn_ = os.path.join(__opts__['cachedir'], 'module_refresh') try: with salt.utils.files.flopen(fn_, 'w+'): pass except (IOError, OSError): log.error( 'Unable to write to cache file %s. Check permissions.', fn_ ) if not __opts__.get('local', False): # Refresh the grains __salt__['saltutil.refresh_grains']() # Return the grains we just set to confirm everything was OK return new_grains
[ "def", "setvals", "(", "grains", ",", "destructive", "=", "False", ")", ":", "new_grains", "=", "grains", "if", "not", "isinstance", "(", "new_grains", ",", "collections", ".", "Mapping", ")", ":", "raise", "SaltException", "(", "'setvals grains must be a dictio...
Set new grains values in the grains config file destructive If an operation results in a key being removed, delete the key, too. Defaults to False. CLI Example: .. code-block:: bash salt '*' grains.setvals "{'key1': 'val1', 'key2': 'val2'}"
[ "Set", "new", "grains", "values", "in", "the", "grains", "config", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L214-L310
train
saltstack/salt
salt/modules/grains.py
append
def append(key, val, convert=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.17.0 Append a value to a list in the grains config file. If the grain doesn't exist, the grain key is added and the value is appended to the new grain as a list item. key The grain key to be appended to val The value to append to the grain key convert If convert is True, convert non-list contents into a list. If convert is False and the grain contains non-list contents, an error is given. Defaults to False. delimiter The key can be a nested dict key. Use this parameter to specify the delimiter you use, instead of the default ``:``. You can now append values to a list in nested dictionary grains. If the list doesn't exist at this level, it will be created. .. versionadded:: 2014.7.6 CLI Example: .. code-block:: bash salt '*' grains.append key val ''' grains = get(key, [], delimiter) if convert: if not isinstance(grains, list): grains = [] if grains is None else [grains] if not isinstance(grains, list): return 'The key {0} is not a valid list'.format(key) if val in grains: return 'The val {0} was already in the list {1}'.format(val, key) if isinstance(val, list): for item in val: grains.append(item) else: grains.append(val) while delimiter in key: key, rest = key.rsplit(delimiter, 1) _grain = get(key, _infinitedict(), delimiter) if isinstance(_grain, dict): _grain.update({rest: grains}) grains = _grain return setval(key, grains)
python
def append(key, val, convert=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.17.0 Append a value to a list in the grains config file. If the grain doesn't exist, the grain key is added and the value is appended to the new grain as a list item. key The grain key to be appended to val The value to append to the grain key convert If convert is True, convert non-list contents into a list. If convert is False and the grain contains non-list contents, an error is given. Defaults to False. delimiter The key can be a nested dict key. Use this parameter to specify the delimiter you use, instead of the default ``:``. You can now append values to a list in nested dictionary grains. If the list doesn't exist at this level, it will be created. .. versionadded:: 2014.7.6 CLI Example: .. code-block:: bash salt '*' grains.append key val ''' grains = get(key, [], delimiter) if convert: if not isinstance(grains, list): grains = [] if grains is None else [grains] if not isinstance(grains, list): return 'The key {0} is not a valid list'.format(key) if val in grains: return 'The val {0} was already in the list {1}'.format(val, key) if isinstance(val, list): for item in val: grains.append(item) else: grains.append(val) while delimiter in key: key, rest = key.rsplit(delimiter, 1) _grain = get(key, _infinitedict(), delimiter) if isinstance(_grain, dict): _grain.update({rest: grains}) grains = _grain return setval(key, grains)
[ "def", "append", "(", "key", ",", "val", ",", "convert", "=", "False", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ")", ":", "grains", "=", "get", "(", "key", ",", "[", "]", ",", "delimiter", ")", "if", "convert", ":", "if", "not", "isinstance", "...
.. versionadded:: 0.17.0 Append a value to a list in the grains config file. If the grain doesn't exist, the grain key is added and the value is appended to the new grain as a list item. key The grain key to be appended to val The value to append to the grain key convert If convert is True, convert non-list contents into a list. If convert is False and the grain contains non-list contents, an error is given. Defaults to False. delimiter The key can be a nested dict key. Use this parameter to specify the delimiter you use, instead of the default ``:``. You can now append values to a list in nested dictionary grains. If the list doesn't exist at this level, it will be created. .. versionadded:: 2014.7.6 CLI Example: .. code-block:: bash salt '*' grains.append key val
[ "..", "versionadded", "::", "0", ".", "17", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L337-L391
train
saltstack/salt
salt/modules/grains.py
remove
def remove(key, val, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.17.0 Remove a value from a list in the grains config file key The grain key to remove. val The value to remove. delimiter The key can be a nested dict key. Use this parameter to specify the delimiter you use, instead of the default ``:``. You can now append values to a list in nested dictionary grains. If the list doesn't exist at this level, it will be created. .. versionadded:: 2015.8.2 CLI Example: .. code-block:: bash salt '*' grains.remove key val ''' grains = get(key, [], delimiter) if not isinstance(grains, list): return 'The key {0} is not a valid list'.format(key) if val not in grains: return 'The val {0} was not in the list {1}'.format(val, key) grains.remove(val) while delimiter in key: key, rest = key.rsplit(delimiter, 1) _grain = get(key, None, delimiter) if isinstance(_grain, dict): _grain.update({rest: grains}) grains = _grain return setval(key, grains)
python
def remove(key, val, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.17.0 Remove a value from a list in the grains config file key The grain key to remove. val The value to remove. delimiter The key can be a nested dict key. Use this parameter to specify the delimiter you use, instead of the default ``:``. You can now append values to a list in nested dictionary grains. If the list doesn't exist at this level, it will be created. .. versionadded:: 2015.8.2 CLI Example: .. code-block:: bash salt '*' grains.remove key val ''' grains = get(key, [], delimiter) if not isinstance(grains, list): return 'The key {0} is not a valid list'.format(key) if val not in grains: return 'The val {0} was not in the list {1}'.format(val, key) grains.remove(val) while delimiter in key: key, rest = key.rsplit(delimiter, 1) _grain = get(key, None, delimiter) if isinstance(_grain, dict): _grain.update({rest: grains}) grains = _grain return setval(key, grains)
[ "def", "remove", "(", "key", ",", "val", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ")", ":", "grains", "=", "get", "(", "key", ",", "[", "]", ",", "delimiter", ")", "if", "not", "isinstance", "(", "grains", ",", "list", ")", ":", "return", "'The...
.. versionadded:: 0.17.0 Remove a value from a list in the grains config file key The grain key to remove. val The value to remove. delimiter The key can be a nested dict key. Use this parameter to specify the delimiter you use, instead of the default ``:``. You can now append values to a list in nested dictionary grains. If the list doesn't exist at this level, it will be created. .. versionadded:: 2015.8.2 CLI Example: .. code-block:: bash salt '*' grains.remove key val
[ "..", "versionadded", "::", "0", ".", "17", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L394-L434
train
saltstack/salt
salt/modules/grains.py
filter_by
def filter_by(lookup_dict, grain='os_family', merge=None, default='default', base=None): ''' .. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be useful at the CLI, the primary intent of this function is for use in Jinja to make short work of creating lookup tables for OS-specific data. For example: .. code-block:: jinja {% set apache = salt['grains.filter_by']({ 'Debian': {'pkg': 'apache2', 'srv': 'apache2'}, 'RedHat': {'pkg': 'httpd', 'srv': 'httpd'}, }, default='Debian') %} myapache: pkg.installed: - name: {{ apache.pkg }} service.running: - name: {{ apache.srv }} Values in the lookup table may be overridden by values in Pillar. An example Pillar to override values in the example above could be as follows: .. code-block:: yaml apache: lookup: pkg: apache_13 srv: apache The call to ``filter_by()`` would be modified as follows to reference those Pillar values: .. code-block:: jinja {% set apache = salt['grains.filter_by']({ ... }, merge=salt['pillar.get']('apache:lookup')) %} :param lookup_dict: A dictionary, keyed by a grain, containing a value or values relevant to systems matching that grain. For example, a key could be the grain for an OS and the value could the name of a package on that particular OS. .. versionchanged:: 2016.11.0 The dictionary key could be a globbing pattern. The function will return the corresponding ``lookup_dict`` value where grain value matches the pattern. For example: .. code-block:: bash # this will render 'got some salt' if Minion ID begins from 'salt' salt '*' grains.filter_by '{salt*: got some salt, default: salt is not here}' id :param grain: The name of a grain to match with the current system's grains. For example, the value of the "os_family" grain for the current system could be used to pull values from the ``lookup_dict`` dictionary. .. versionchanged:: 2016.11.0 The grain value could be a list. The function will return the ``lookup_dict`` value for a first found item in the list matching one of the ``lookup_dict`` keys. :param merge: A dictionary to merge with the results of the grain selection from ``lookup_dict``. This allows Pillar to override the values in the ``lookup_dict``. This could be useful, for example, to override the values for non-standard package names such as when using a different Python version from the default Python version provided by the OS (e.g., ``python26-mysql`` instead of ``python-mysql``). :param default: default lookup_dict's key used if the grain does not exists or if the grain value has no match on lookup_dict. If unspecified the value is "default". .. versionadded:: 2014.1.0 :param base: A lookup_dict key to use for a base dictionary. The grain-selected ``lookup_dict`` is merged over this and then finally the ``merge`` dictionary is merged. This allows common values for each case to be collected in the base and overridden by the grain selection dictionary and the merge dictionary. Default is unset. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' grains.filter_by '{Debian: Debheads rule, RedHat: I love my hat}' # this one will render {D: {E: I, G: H}, J: K} salt '*' grains.filter_by '{A: B, C: {D: {E: F, G: H}}}' 'xxx' '{D: {E: I}, J: K}' 'C' # next one renders {A: {B: G}, D: J} salt '*' grains.filter_by '{default: {A: {B: C}, D: E}, F: {A: {B: G}}, H: {D: I}}' 'xxx' '{D: J}' 'F' 'default' # next same as above when default='H' instead of 'F' renders {A: {B: C}, D: J} ''' return salt.utils.data.filter_by(lookup_dict=lookup_dict, lookup=grain, traverse=__grains__, merge=merge, default=default, base=base)
python
def filter_by(lookup_dict, grain='os_family', merge=None, default='default', base=None): ''' .. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be useful at the CLI, the primary intent of this function is for use in Jinja to make short work of creating lookup tables for OS-specific data. For example: .. code-block:: jinja {% set apache = salt['grains.filter_by']({ 'Debian': {'pkg': 'apache2', 'srv': 'apache2'}, 'RedHat': {'pkg': 'httpd', 'srv': 'httpd'}, }, default='Debian') %} myapache: pkg.installed: - name: {{ apache.pkg }} service.running: - name: {{ apache.srv }} Values in the lookup table may be overridden by values in Pillar. An example Pillar to override values in the example above could be as follows: .. code-block:: yaml apache: lookup: pkg: apache_13 srv: apache The call to ``filter_by()`` would be modified as follows to reference those Pillar values: .. code-block:: jinja {% set apache = salt['grains.filter_by']({ ... }, merge=salt['pillar.get']('apache:lookup')) %} :param lookup_dict: A dictionary, keyed by a grain, containing a value or values relevant to systems matching that grain. For example, a key could be the grain for an OS and the value could the name of a package on that particular OS. .. versionchanged:: 2016.11.0 The dictionary key could be a globbing pattern. The function will return the corresponding ``lookup_dict`` value where grain value matches the pattern. For example: .. code-block:: bash # this will render 'got some salt' if Minion ID begins from 'salt' salt '*' grains.filter_by '{salt*: got some salt, default: salt is not here}' id :param grain: The name of a grain to match with the current system's grains. For example, the value of the "os_family" grain for the current system could be used to pull values from the ``lookup_dict`` dictionary. .. versionchanged:: 2016.11.0 The grain value could be a list. The function will return the ``lookup_dict`` value for a first found item in the list matching one of the ``lookup_dict`` keys. :param merge: A dictionary to merge with the results of the grain selection from ``lookup_dict``. This allows Pillar to override the values in the ``lookup_dict``. This could be useful, for example, to override the values for non-standard package names such as when using a different Python version from the default Python version provided by the OS (e.g., ``python26-mysql`` instead of ``python-mysql``). :param default: default lookup_dict's key used if the grain does not exists or if the grain value has no match on lookup_dict. If unspecified the value is "default". .. versionadded:: 2014.1.0 :param base: A lookup_dict key to use for a base dictionary. The grain-selected ``lookup_dict`` is merged over this and then finally the ``merge`` dictionary is merged. This allows common values for each case to be collected in the base and overridden by the grain selection dictionary and the merge dictionary. Default is unset. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' grains.filter_by '{Debian: Debheads rule, RedHat: I love my hat}' # this one will render {D: {E: I, G: H}, J: K} salt '*' grains.filter_by '{A: B, C: {D: {E: F, G: H}}}' 'xxx' '{D: {E: I}, J: K}' 'C' # next one renders {A: {B: G}, D: J} salt '*' grains.filter_by '{default: {A: {B: C}, D: E}, F: {A: {B: G}}, H: {D: I}}' 'xxx' '{D: J}' 'F' 'default' # next same as above when default='H' instead of 'F' renders {A: {B: C}, D: J} ''' return salt.utils.data.filter_by(lookup_dict=lookup_dict, lookup=grain, traverse=__grains__, merge=merge, default=default, base=base)
[ "def", "filter_by", "(", "lookup_dict", ",", "grain", "=", "'os_family'", ",", "merge", "=", "None", ",", "default", "=", "'default'", ",", "base", "=", "None", ")", ":", "return", "salt", ".", "utils", ".", "data", ".", "filter_by", "(", "lookup_dict", ...
.. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be useful at the CLI, the primary intent of this function is for use in Jinja to make short work of creating lookup tables for OS-specific data. For example: .. code-block:: jinja {% set apache = salt['grains.filter_by']({ 'Debian': {'pkg': 'apache2', 'srv': 'apache2'}, 'RedHat': {'pkg': 'httpd', 'srv': 'httpd'}, }, default='Debian') %} myapache: pkg.installed: - name: {{ apache.pkg }} service.running: - name: {{ apache.srv }} Values in the lookup table may be overridden by values in Pillar. An example Pillar to override values in the example above could be as follows: .. code-block:: yaml apache: lookup: pkg: apache_13 srv: apache The call to ``filter_by()`` would be modified as follows to reference those Pillar values: .. code-block:: jinja {% set apache = salt['grains.filter_by']({ ... }, merge=salt['pillar.get']('apache:lookup')) %} :param lookup_dict: A dictionary, keyed by a grain, containing a value or values relevant to systems matching that grain. For example, a key could be the grain for an OS and the value could the name of a package on that particular OS. .. versionchanged:: 2016.11.0 The dictionary key could be a globbing pattern. The function will return the corresponding ``lookup_dict`` value where grain value matches the pattern. For example: .. code-block:: bash # this will render 'got some salt' if Minion ID begins from 'salt' salt '*' grains.filter_by '{salt*: got some salt, default: salt is not here}' id :param grain: The name of a grain to match with the current system's grains. For example, the value of the "os_family" grain for the current system could be used to pull values from the ``lookup_dict`` dictionary. .. versionchanged:: 2016.11.0 The grain value could be a list. The function will return the ``lookup_dict`` value for a first found item in the list matching one of the ``lookup_dict`` keys. :param merge: A dictionary to merge with the results of the grain selection from ``lookup_dict``. This allows Pillar to override the values in the ``lookup_dict``. This could be useful, for example, to override the values for non-standard package names such as when using a different Python version from the default Python version provided by the OS (e.g., ``python26-mysql`` instead of ``python-mysql``). :param default: default lookup_dict's key used if the grain does not exists or if the grain value has no match on lookup_dict. If unspecified the value is "default". .. versionadded:: 2014.1.0 :param base: A lookup_dict key to use for a base dictionary. The grain-selected ``lookup_dict`` is merged over this and then finally the ``merge`` dictionary is merged. This allows common values for each case to be collected in the base and overridden by the grain selection dictionary and the merge dictionary. Default is unset. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' grains.filter_by '{Debian: Debheads rule, RedHat: I love my hat}' # this one will render {D: {E: I, G: H}, J: K} salt '*' grains.filter_by '{A: B, C: {D: {E: F, G: H}}}' 'xxx' '{D: {E: I}, J: K}' 'C' # next one renders {A: {B: G}, D: J} salt '*' grains.filter_by '{default: {A: {B: C}, D: E}, F: {A: {B: G}}, H: {D: I}}' 'xxx' '{D: J}' 'F' 'default' # next same as above when default='H' instead of 'F' renders {A: {B: C}, D: J}
[ "..", "versionadded", "::", "0", ".", "17", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L492-L600
train
saltstack/salt
salt/modules/grains.py
_dict_from_path
def _dict_from_path(path, val, delimiter=DEFAULT_TARGET_DELIM): ''' Given a lookup string in the form of 'foo:bar:baz" return a nested dictionary of the appropriate depth with the final segment as a value. >>> _dict_from_path('foo:bar:baz', 'somevalue') {"foo": {"bar": {"baz": "somevalue"}} ''' nested_dict = _infinitedict() keys = path.rsplit(delimiter) lastplace = reduce(operator.getitem, keys[:-1], nested_dict) lastplace[keys[-1]] = val return nested_dict
python
def _dict_from_path(path, val, delimiter=DEFAULT_TARGET_DELIM): ''' Given a lookup string in the form of 'foo:bar:baz" return a nested dictionary of the appropriate depth with the final segment as a value. >>> _dict_from_path('foo:bar:baz', 'somevalue') {"foo": {"bar": {"baz": "somevalue"}} ''' nested_dict = _infinitedict() keys = path.rsplit(delimiter) lastplace = reduce(operator.getitem, keys[:-1], nested_dict) lastplace[keys[-1]] = val return nested_dict
[ "def", "_dict_from_path", "(", "path", ",", "val", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ")", ":", "nested_dict", "=", "_infinitedict", "(", ")", "keys", "=", "path", ".", "rsplit", "(", "delimiter", ")", "lastplace", "=", "reduce", "(", "operator",...
Given a lookup string in the form of 'foo:bar:baz" return a nested dictionary of the appropriate depth with the final segment as a value. >>> _dict_from_path('foo:bar:baz', 'somevalue') {"foo": {"bar": {"baz": "somevalue"}}
[ "Given", "a", "lookup", "string", "in", "the", "form", "of", "foo", ":", "bar", ":", "baz", "return", "a", "nested", "dictionary", "of", "the", "appropriate", "depth", "with", "the", "final", "segment", "as", "a", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L603-L616
train
saltstack/salt
salt/modules/grains.py
get_or_set_hash
def get_or_set_hash(name, length=8, chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'): ''' Perform a one-time generation of a hash and write it to the local grains. If that grain has already been set return the value instead. This is useful for generating passwords or keys that are specific to a single minion that don't need to be stored somewhere centrally. State Example: .. code-block:: yaml some_mysql_user: mysql_user: - present - host: localhost - password: {{ salt['grains.get_or_set_hash']('mysql:some_mysql_user') }} CLI Example: .. code-block:: bash salt '*' grains.get_or_set_hash 'django:SECRET_KEY' 50 .. warning:: This function could return strings which may contain characters which are reserved as directives by the YAML parser, such as strings beginning with ``%``. To avoid issues when using the output of this function in an SLS file containing YAML+Jinja, surround the call with single quotes. ''' ret = get(name, None) if ret is None: val = ''.join([random.SystemRandom().choice(chars) for _ in range(length)]) if DEFAULT_TARGET_DELIM in name: root, rest = name.split(DEFAULT_TARGET_DELIM, 1) curr = get(root, _infinitedict()) val = _dict_from_path(rest, val) curr.update(val) setval(root, curr) else: setval(name, val) return get(name)
python
def get_or_set_hash(name, length=8, chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'): ''' Perform a one-time generation of a hash and write it to the local grains. If that grain has already been set return the value instead. This is useful for generating passwords or keys that are specific to a single minion that don't need to be stored somewhere centrally. State Example: .. code-block:: yaml some_mysql_user: mysql_user: - present - host: localhost - password: {{ salt['grains.get_or_set_hash']('mysql:some_mysql_user') }} CLI Example: .. code-block:: bash salt '*' grains.get_or_set_hash 'django:SECRET_KEY' 50 .. warning:: This function could return strings which may contain characters which are reserved as directives by the YAML parser, such as strings beginning with ``%``. To avoid issues when using the output of this function in an SLS file containing YAML+Jinja, surround the call with single quotes. ''' ret = get(name, None) if ret is None: val = ''.join([random.SystemRandom().choice(chars) for _ in range(length)]) if DEFAULT_TARGET_DELIM in name: root, rest = name.split(DEFAULT_TARGET_DELIM, 1) curr = get(root, _infinitedict()) val = _dict_from_path(rest, val) curr.update(val) setval(root, curr) else: setval(name, val) return get(name)
[ "def", "get_or_set_hash", "(", "name", ",", "length", "=", "8", ",", "chars", "=", "'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'", ")", ":", "ret", "=", "get", "(", "name", ",", "None", ")", "if", "ret", "is", "None", ":", "val", "=", "''", ".", ...
Perform a one-time generation of a hash and write it to the local grains. If that grain has already been set return the value instead. This is useful for generating passwords or keys that are specific to a single minion that don't need to be stored somewhere centrally. State Example: .. code-block:: yaml some_mysql_user: mysql_user: - present - host: localhost - password: {{ salt['grains.get_or_set_hash']('mysql:some_mysql_user') }} CLI Example: .. code-block:: bash salt '*' grains.get_or_set_hash 'django:SECRET_KEY' 50 .. warning:: This function could return strings which may contain characters which are reserved as directives by the YAML parser, such as strings beginning with ``%``. To avoid issues when using the output of this function in an SLS file containing YAML+Jinja, surround the call with single quotes.
[ "Perform", "a", "one", "-", "time", "generation", "of", "a", "hash", "and", "write", "it", "to", "the", "local", "grains", ".", "If", "that", "grain", "has", "already", "been", "set", "return", "the", "value", "instead", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L619-L666
train
saltstack/salt
salt/modules/grains.py
set
def set(key, val='', force=False, destructive=False, delimiter=DEFAULT_TARGET_DELIM): ''' Set a key to an arbitrary value. It is used like setval but works with nested keys. This function is conservative. It will only overwrite an entry if its value and the given one are not a list or a dict. The ``force`` parameter is used to allow overwriting in all cases. .. versionadded:: 2015.8.0 :param force: Force writing over existing entry if given or existing values are list or dict. Defaults to False. :param destructive: If an operation results in a key being removed, delete the key, too. Defaults to False. :param delimiter: Specify an alternate delimiter to use when traversing a nested dict, the default being ``:`` CLI Example: .. code-block:: bash salt '*' grains.set 'apps:myApp:port' 2209 salt '*' grains.set 'apps:myApp' '{port: 2209}' ''' ret = {'comment': '', 'changes': {}, 'result': True} # Get val type _new_value_type = 'simple' if isinstance(val, dict): _new_value_type = 'complex' elif isinstance(val, list): _new_value_type = 'complex' _non_existent = object() _existing_value = get(key, _non_existent, delimiter) _value = _existing_value _existing_value_type = 'simple' if _existing_value is _non_existent: _existing_value_type = None elif isinstance(_existing_value, dict): _existing_value_type = 'complex' elif isinstance(_existing_value, list): _existing_value_type = 'complex' if _existing_value_type is not None and _existing_value == val \ and (val is not None or destructive is not True): ret['comment'] = 'Grain is already set' return ret if _existing_value is not None and not force: if _existing_value_type == 'complex': ret['comment'] = ( 'The key \'{0}\' exists but is a dict or a list. ' 'Use \'force=True\' to overwrite.'.format(key) ) ret['result'] = False return ret elif _new_value_type == 'complex' and _existing_value_type is not None: ret['comment'] = ( 'The key \'{0}\' exists and the given value is a dict or a ' 'list. Use \'force=True\' to overwrite.'.format(key) ) ret['result'] = False return ret else: _value = val else: _value = val # Process nested grains while delimiter in key: key, rest = key.rsplit(delimiter, 1) _existing_value = get(key, {}, delimiter) if isinstance(_existing_value, dict): if _value is None and destructive: if rest in _existing_value.keys(): _existing_value.pop(rest) else: _existing_value.update({rest: _value}) elif isinstance(_existing_value, list): _list_updated = False for _index, _item in enumerate(_existing_value): if _item == rest: _existing_value[_index] = {rest: _value} _list_updated = True elif isinstance(_item, dict) and rest in _item: _item.update({rest: _value}) _list_updated = True if not _list_updated: _existing_value.append({rest: _value}) elif _existing_value == rest or force: _existing_value = {rest: _value} else: ret['comment'] = ( 'The key \'{0}\' value is \'{1}\', which is different from ' 'the provided key \'{2}\'. Use \'force=True\' to overwrite.' .format(key, _existing_value, rest) ) ret['result'] = False return ret _value = _existing_value _setval_ret = setval(key, _value, destructive=destructive) if isinstance(_setval_ret, dict): ret['changes'] = _setval_ret else: ret['comment'] = _setval_ret ret['result'] = False return ret
python
def set(key, val='', force=False, destructive=False, delimiter=DEFAULT_TARGET_DELIM): ''' Set a key to an arbitrary value. It is used like setval but works with nested keys. This function is conservative. It will only overwrite an entry if its value and the given one are not a list or a dict. The ``force`` parameter is used to allow overwriting in all cases. .. versionadded:: 2015.8.0 :param force: Force writing over existing entry if given or existing values are list or dict. Defaults to False. :param destructive: If an operation results in a key being removed, delete the key, too. Defaults to False. :param delimiter: Specify an alternate delimiter to use when traversing a nested dict, the default being ``:`` CLI Example: .. code-block:: bash salt '*' grains.set 'apps:myApp:port' 2209 salt '*' grains.set 'apps:myApp' '{port: 2209}' ''' ret = {'comment': '', 'changes': {}, 'result': True} # Get val type _new_value_type = 'simple' if isinstance(val, dict): _new_value_type = 'complex' elif isinstance(val, list): _new_value_type = 'complex' _non_existent = object() _existing_value = get(key, _non_existent, delimiter) _value = _existing_value _existing_value_type = 'simple' if _existing_value is _non_existent: _existing_value_type = None elif isinstance(_existing_value, dict): _existing_value_type = 'complex' elif isinstance(_existing_value, list): _existing_value_type = 'complex' if _existing_value_type is not None and _existing_value == val \ and (val is not None or destructive is not True): ret['comment'] = 'Grain is already set' return ret if _existing_value is not None and not force: if _existing_value_type == 'complex': ret['comment'] = ( 'The key \'{0}\' exists but is a dict or a list. ' 'Use \'force=True\' to overwrite.'.format(key) ) ret['result'] = False return ret elif _new_value_type == 'complex' and _existing_value_type is not None: ret['comment'] = ( 'The key \'{0}\' exists and the given value is a dict or a ' 'list. Use \'force=True\' to overwrite.'.format(key) ) ret['result'] = False return ret else: _value = val else: _value = val # Process nested grains while delimiter in key: key, rest = key.rsplit(delimiter, 1) _existing_value = get(key, {}, delimiter) if isinstance(_existing_value, dict): if _value is None and destructive: if rest in _existing_value.keys(): _existing_value.pop(rest) else: _existing_value.update({rest: _value}) elif isinstance(_existing_value, list): _list_updated = False for _index, _item in enumerate(_existing_value): if _item == rest: _existing_value[_index] = {rest: _value} _list_updated = True elif isinstance(_item, dict) and rest in _item: _item.update({rest: _value}) _list_updated = True if not _list_updated: _existing_value.append({rest: _value}) elif _existing_value == rest or force: _existing_value = {rest: _value} else: ret['comment'] = ( 'The key \'{0}\' value is \'{1}\', which is different from ' 'the provided key \'{2}\'. Use \'force=True\' to overwrite.' .format(key, _existing_value, rest) ) ret['result'] = False return ret _value = _existing_value _setval_ret = setval(key, _value, destructive=destructive) if isinstance(_setval_ret, dict): ret['changes'] = _setval_ret else: ret['comment'] = _setval_ret ret['result'] = False return ret
[ "def", "set", "(", "key", ",", "val", "=", "''", ",", "force", "=", "False", ",", "destructive", "=", "False", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ")", ":", "ret", "=", "{", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", ",", "...
Set a key to an arbitrary value. It is used like setval but works with nested keys. This function is conservative. It will only overwrite an entry if its value and the given one are not a list or a dict. The ``force`` parameter is used to allow overwriting in all cases. .. versionadded:: 2015.8.0 :param force: Force writing over existing entry if given or existing values are list or dict. Defaults to False. :param destructive: If an operation results in a key being removed, delete the key, too. Defaults to False. :param delimiter: Specify an alternate delimiter to use when traversing a nested dict, the default being ``:`` CLI Example: .. code-block:: bash salt '*' grains.set 'apps:myApp:port' 2209 salt '*' grains.set 'apps:myApp' '{port: 2209}'
[ "Set", "a", "key", "to", "an", "arbitrary", "value", ".", "It", "is", "used", "like", "setval", "but", "works", "with", "nested", "keys", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L669-L787
train
saltstack/salt
salt/modules/grains.py
equals
def equals(key, value): ''' Used to make sure the minion's grain key/value matches. Returns ``True`` if matches otherwise ``False``. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' grains.equals fqdn <expected_fqdn> salt '*' grains.equals systemd:version 219 ''' return six.text_type(value) == six.text_type(get(key))
python
def equals(key, value): ''' Used to make sure the minion's grain key/value matches. Returns ``True`` if matches otherwise ``False``. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' grains.equals fqdn <expected_fqdn> salt '*' grains.equals systemd:version 219 ''' return six.text_type(value) == six.text_type(get(key))
[ "def", "equals", "(", "key", ",", "value", ")", ":", "return", "six", ".", "text_type", "(", "value", ")", "==", "six", ".", "text_type", "(", "get", "(", "key", ")", ")" ]
Used to make sure the minion's grain key/value matches. Returns ``True`` if matches otherwise ``False``. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' grains.equals fqdn <expected_fqdn> salt '*' grains.equals systemd:version 219
[ "Used", "to", "make", "sure", "the", "minion", "s", "grain", "key", "/", "value", "matches", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grains.py#L790-L805
train
saltstack/salt
salt/modules/xapi_virt.py
_get_xapi_session
def _get_xapi_session(): ''' Get a session to XenAPI. By default, use the local UNIX socket. ''' _xenapi = _check_xenapi() xapi_uri = __salt__['config.option']('xapi.uri') xapi_login = __salt__['config.option']('xapi.login') xapi_password = __salt__['config.option']('xapi.password') if not xapi_uri: # xend local UNIX socket xapi_uri = 'httpu:///var/run/xend/xen-api.sock' if not xapi_login: xapi_login = '' if not xapi_password: xapi_password = '' try: session = _xenapi.Session(xapi_uri) session.xenapi.login_with_password(xapi_login, xapi_password) yield session.xenapi except Exception: raise CommandExecutionError('Failed to connect to XenAPI socket.') finally: session.xenapi.session.logout()
python
def _get_xapi_session(): ''' Get a session to XenAPI. By default, use the local UNIX socket. ''' _xenapi = _check_xenapi() xapi_uri = __salt__['config.option']('xapi.uri') xapi_login = __salt__['config.option']('xapi.login') xapi_password = __salt__['config.option']('xapi.password') if not xapi_uri: # xend local UNIX socket xapi_uri = 'httpu:///var/run/xend/xen-api.sock' if not xapi_login: xapi_login = '' if not xapi_password: xapi_password = '' try: session = _xenapi.Session(xapi_uri) session.xenapi.login_with_password(xapi_login, xapi_password) yield session.xenapi except Exception: raise CommandExecutionError('Failed to connect to XenAPI socket.') finally: session.xenapi.session.logout()
[ "def", "_get_xapi_session", "(", ")", ":", "_xenapi", "=", "_check_xenapi", "(", ")", "xapi_uri", "=", "__salt__", "[", "'config.option'", "]", "(", "'xapi.uri'", ")", "xapi_login", "=", "__salt__", "[", "'config.option'", "]", "(", "'xapi.login'", ")", "xapi_...
Get a session to XenAPI. By default, use the local UNIX socket.
[ "Get", "a", "session", "to", "XenAPI", ".", "By", "default", "use", "the", "local", "UNIX", "socket", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L76-L102
train
saltstack/salt
salt/modules/xapi_virt.py
_get_xtool
def _get_xtool(): ''' Internal, returns xl or xm command line path ''' for xtool in ['xl', 'xm']: path = salt.utils.path.which(xtool) if path is not None: return path
python
def _get_xtool(): ''' Internal, returns xl or xm command line path ''' for xtool in ['xl', 'xm']: path = salt.utils.path.which(xtool) if path is not None: return path
[ "def", "_get_xtool", "(", ")", ":", "for", "xtool", "in", "[", "'xl'", ",", "'xm'", "]", ":", "path", "=", "salt", ".", "utils", ".", "path", ".", "which", "(", "xtool", ")", "if", "path", "is", "not", "None", ":", "return", "path" ]
Internal, returns xl or xm command line path
[ "Internal", "returns", "xl", "or", "xm", "command", "line", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L114-L121
train
saltstack/salt
salt/modules/xapi_virt.py
_get_label_uuid
def _get_label_uuid(xapi, rectype, label): ''' Internal, returns label's uuid ''' try: return getattr(xapi, rectype).get_by_name_label(label)[0] except Exception: return False
python
def _get_label_uuid(xapi, rectype, label): ''' Internal, returns label's uuid ''' try: return getattr(xapi, rectype).get_by_name_label(label)[0] except Exception: return False
[ "def", "_get_label_uuid", "(", "xapi", ",", "rectype", ",", "label", ")", ":", "try", ":", "return", "getattr", "(", "xapi", ",", "rectype", ")", ".", "get_by_name_label", "(", "label", ")", "[", "0", "]", "except", "Exception", ":", "return", "False" ]
Internal, returns label's uuid
[ "Internal", "returns", "label", "s", "uuid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L131-L138
train
saltstack/salt
salt/modules/xapi_virt.py
_get_record_by_label
def _get_record_by_label(xapi, rectype, label): ''' Internal, returns a full record for uuid ''' uuid = _get_label_uuid(xapi, rectype, label) if uuid is False: return False return getattr(xapi, rectype).get_record(uuid)
python
def _get_record_by_label(xapi, rectype, label): ''' Internal, returns a full record for uuid ''' uuid = _get_label_uuid(xapi, rectype, label) if uuid is False: return False return getattr(xapi, rectype).get_record(uuid)
[ "def", "_get_record_by_label", "(", "xapi", ",", "rectype", ",", "label", ")", ":", "uuid", "=", "_get_label_uuid", "(", "xapi", ",", "rectype", ",", "label", ")", "if", "uuid", "is", "False", ":", "return", "False", "return", "getattr", "(", "xapi", ","...
Internal, returns a full record for uuid
[ "Internal", "returns", "a", "full", "record", "for", "uuid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L148-L155
train
saltstack/salt
salt/modules/xapi_virt.py
_get_metrics_record
def _get_metrics_record(xapi, rectype, record): ''' Internal, returns metrics record for a rectype ''' metrics_id = record['metrics'] return getattr(xapi, '{0}_metrics'.format(rectype)).get_record(metrics_id)
python
def _get_metrics_record(xapi, rectype, record): ''' Internal, returns metrics record for a rectype ''' metrics_id = record['metrics'] return getattr(xapi, '{0}_metrics'.format(rectype)).get_record(metrics_id)
[ "def", "_get_metrics_record", "(", "xapi", ",", "rectype", ",", "record", ")", ":", "metrics_id", "=", "record", "[", "'metrics'", "]", "return", "getattr", "(", "xapi", ",", "'{0}_metrics'", ".", "format", "(", "rectype", ")", ")", ".", "get_record", "(",...
Internal, returns metrics record for a rectype
[ "Internal", "returns", "metrics", "record", "for", "a", "rectype" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L158-L163
train
saltstack/salt
salt/modules/xapi_virt.py
_get_val
def _get_val(record, keys): ''' Internal, get value from record ''' data = record for key in keys: if key in data: data = data[key] else: return None return data
python
def _get_val(record, keys): ''' Internal, get value from record ''' data = record for key in keys: if key in data: data = data[key] else: return None return data
[ "def", "_get_val", "(", "record", ",", "keys", ")", ":", "data", "=", "record", "for", "key", "in", "keys", ":", "if", "key", "in", "data", ":", "data", "=", "data", "[", "key", "]", "else", ":", "return", "None", "return", "data" ]
Internal, get value from record
[ "Internal", "get", "value", "from", "record" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L166-L176
train
saltstack/salt
salt/modules/xapi_virt.py
list_domains
def list_domains(): ''' Return a list of virtual machine names on the minion CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' with _get_xapi_session() as xapi: hosts = xapi.VM.get_all() ret = [] for _host in hosts: if xapi.VM.get_record(_host)['is_control_domain'] is False: ret.append(xapi.VM.get_name_label(_host)) return ret
python
def list_domains(): ''' Return a list of virtual machine names on the minion CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' with _get_xapi_session() as xapi: hosts = xapi.VM.get_all() ret = [] for _host in hosts: if xapi.VM.get_record(_host)['is_control_domain'] is False: ret.append(xapi.VM.get_name_label(_host)) return ret
[ "def", "list_domains", "(", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "hosts", "=", "xapi", ".", "VM", ".", "get_all", "(", ")", "ret", "=", "[", "]", "for", "_host", "in", "hosts", ":", "if", "xapi", ".", "VM", ".", "ge...
Return a list of virtual machine names on the minion CLI Example: .. code-block:: bash salt '*' virt.list_domains
[ "Return", "a", "list", "of", "virtual", "machine", "names", "on", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L179-L197
train
saltstack/salt
salt/modules/xapi_virt.py
vm_info
def vm_info(vm_=None): ''' Return detailed information about the vms. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' with _get_xapi_session() as xapi: def _info(vm_): vm_rec = _get_record_by_label(xapi, 'VM', vm_) if vm_rec is False: return False vm_metrics_rec = _get_metrics_record(xapi, 'VM', vm_rec) return {'cpu': vm_metrics_rec['VCPUs_number'], 'maxCPU': _get_val(vm_rec, ['VCPUs_max']), 'cputime': vm_metrics_rec['VCPUs_utilisation'], 'disks': get_disks(vm_), 'nics': get_nics(vm_), 'maxMem': int(_get_val(vm_rec, ['memory_dynamic_max'])), 'mem': int(vm_metrics_rec['memory_actual']), 'state': _get_val(vm_rec, ['power_state']) } info = {} if vm_: ret = _info(vm_) if ret is not None: info[vm_] = ret else: for vm_ in list_domains(): ret = _info(vm_) if ret is not None: info[vm_] = _info(vm_) return info
python
def vm_info(vm_=None): ''' Return detailed information about the vms. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' with _get_xapi_session() as xapi: def _info(vm_): vm_rec = _get_record_by_label(xapi, 'VM', vm_) if vm_rec is False: return False vm_metrics_rec = _get_metrics_record(xapi, 'VM', vm_rec) return {'cpu': vm_metrics_rec['VCPUs_number'], 'maxCPU': _get_val(vm_rec, ['VCPUs_max']), 'cputime': vm_metrics_rec['VCPUs_utilisation'], 'disks': get_disks(vm_), 'nics': get_nics(vm_), 'maxMem': int(_get_val(vm_rec, ['memory_dynamic_max'])), 'mem': int(vm_metrics_rec['memory_actual']), 'state': _get_val(vm_rec, ['power_state']) } info = {} if vm_: ret = _info(vm_) if ret is not None: info[vm_] = ret else: for vm_ in list_domains(): ret = _info(vm_) if ret is not None: info[vm_] = _info(vm_) return info
[ "def", "vm_info", "(", "vm_", "=", "None", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "def", "_info", "(", "vm_", ")", ":", "vm_rec", "=", "_get_record_by_label", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_rec", "is...
Return detailed information about the vms. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info
[ "Return", "detailed", "information", "about", "the", "vms", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L200-L240
train
saltstack/salt
salt/modules/xapi_virt.py
vm_state
def vm_state(vm_=None): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_state <vm name> ''' with _get_xapi_session() as xapi: info = {} if vm_: info[vm_] = _get_record_by_label(xapi, 'VM', vm_)['power_state'] return info for vm_ in list_domains(): info[vm_] = _get_record_by_label(xapi, 'VM', vm_)['power_state'] return info
python
def vm_state(vm_=None): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_state <vm name> ''' with _get_xapi_session() as xapi: info = {} if vm_: info[vm_] = _get_record_by_label(xapi, 'VM', vm_)['power_state'] return info for vm_ in list_domains(): info[vm_] = _get_record_by_label(xapi, 'VM', vm_)['power_state'] return info
[ "def", "vm_state", "(", "vm_", "=", "None", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "info", "=", "{", "}", "if", "vm_", ":", "info", "[", "vm_", "]", "=", "_get_record_by_label", "(", "xapi", ",", "'VM'", ",", "vm_", ")"...
Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_state <vm name>
[ "Return", "list", "of", "all", "the", "vms", "and", "their", "state", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L243-L265
train
saltstack/salt
salt/modules/xapi_virt.py
node_info
def node_info(): ''' Return a dict with information about this node CLI Example: .. code-block:: bash salt '*' virt.node_info ''' with _get_xapi_session() as xapi: # get node uuid host_rec = _get_record(xapi, 'host', _get_all(xapi, 'host')[0]) # get first CPU (likely to be a core) uuid host_cpu_rec = _get_record(xapi, 'host_cpu', host_rec['host_CPUs'][0]) # get related metrics host_metrics_rec = _get_metrics_record(xapi, 'host', host_rec) # adapted / cleaned up from Xen's xm def getCpuMhz(): cpu_speeds = [int(host_cpu_rec["speed"]) for host_cpu_it in host_cpu_rec if "speed" in host_cpu_it] if cpu_speeds: return sum(cpu_speeds) / len(cpu_speeds) else: return 0 def getCpuFeatures(): if host_cpu_rec: return host_cpu_rec['features'] def getFreeCpuCount(): cnt = 0 for host_cpu_it in host_cpu_rec: if not host_cpu_rec['cpu_pool']: cnt += 1 return cnt info = { 'cpucores': _get_val(host_rec, ["cpu_configuration", "nr_cpus"]), 'cpufeatures': getCpuFeatures(), 'cpumhz': getCpuMhz(), 'cpuarch': _get_val(host_rec, ["software_version", "machine"]), 'cputhreads': _get_val(host_rec, ["cpu_configuration", "threads_per_core"]), 'phymemory': int(host_metrics_rec["memory_total"]) / 1024 / 1024, 'cores_per_sockets': _get_val(host_rec, ["cpu_configuration", "cores_per_socket"]), 'free_cpus': getFreeCpuCount(), 'free_memory': int(host_metrics_rec["memory_free"]) / 1024 / 1024, 'xen_major': _get_val(host_rec, ["software_version", "xen_major"]), 'xen_minor': _get_val(host_rec, ["software_version", "xen_minor"]), 'xen_extra': _get_val(host_rec, ["software_version", "xen_extra"]), 'xen_caps': " ".join(_get_val(host_rec, ["capabilities"])), 'xen_scheduler': _get_val(host_rec, ["sched_policy"]), 'xen_pagesize': _get_val(host_rec, ["other_config", "xen_pagesize"]), 'platform_params': _get_val(host_rec, ["other_config", "platform_params"]), 'xen_commandline': _get_val(host_rec, ["other_config", "xen_commandline"]), 'xen_changeset': _get_val(host_rec, ["software_version", "xen_changeset"]), 'cc_compiler': _get_val(host_rec, ["software_version", "cc_compiler"]), 'cc_compile_by': _get_val(host_rec, ["software_version", "cc_compile_by"]), 'cc_compile_domain': _get_val(host_rec, ["software_version", "cc_compile_domain"]), 'cc_compile_date': _get_val(host_rec, ["software_version", "cc_compile_date"]), 'xend_config_format': _get_val(host_rec, ["software_version", "xend_config_format"]) } return info
python
def node_info(): ''' Return a dict with information about this node CLI Example: .. code-block:: bash salt '*' virt.node_info ''' with _get_xapi_session() as xapi: # get node uuid host_rec = _get_record(xapi, 'host', _get_all(xapi, 'host')[0]) # get first CPU (likely to be a core) uuid host_cpu_rec = _get_record(xapi, 'host_cpu', host_rec['host_CPUs'][0]) # get related metrics host_metrics_rec = _get_metrics_record(xapi, 'host', host_rec) # adapted / cleaned up from Xen's xm def getCpuMhz(): cpu_speeds = [int(host_cpu_rec["speed"]) for host_cpu_it in host_cpu_rec if "speed" in host_cpu_it] if cpu_speeds: return sum(cpu_speeds) / len(cpu_speeds) else: return 0 def getCpuFeatures(): if host_cpu_rec: return host_cpu_rec['features'] def getFreeCpuCount(): cnt = 0 for host_cpu_it in host_cpu_rec: if not host_cpu_rec['cpu_pool']: cnt += 1 return cnt info = { 'cpucores': _get_val(host_rec, ["cpu_configuration", "nr_cpus"]), 'cpufeatures': getCpuFeatures(), 'cpumhz': getCpuMhz(), 'cpuarch': _get_val(host_rec, ["software_version", "machine"]), 'cputhreads': _get_val(host_rec, ["cpu_configuration", "threads_per_core"]), 'phymemory': int(host_metrics_rec["memory_total"]) / 1024 / 1024, 'cores_per_sockets': _get_val(host_rec, ["cpu_configuration", "cores_per_socket"]), 'free_cpus': getFreeCpuCount(), 'free_memory': int(host_metrics_rec["memory_free"]) / 1024 / 1024, 'xen_major': _get_val(host_rec, ["software_version", "xen_major"]), 'xen_minor': _get_val(host_rec, ["software_version", "xen_minor"]), 'xen_extra': _get_val(host_rec, ["software_version", "xen_extra"]), 'xen_caps': " ".join(_get_val(host_rec, ["capabilities"])), 'xen_scheduler': _get_val(host_rec, ["sched_policy"]), 'xen_pagesize': _get_val(host_rec, ["other_config", "xen_pagesize"]), 'platform_params': _get_val(host_rec, ["other_config", "platform_params"]), 'xen_commandline': _get_val(host_rec, ["other_config", "xen_commandline"]), 'xen_changeset': _get_val(host_rec, ["software_version", "xen_changeset"]), 'cc_compiler': _get_val(host_rec, ["software_version", "cc_compiler"]), 'cc_compile_by': _get_val(host_rec, ["software_version", "cc_compile_by"]), 'cc_compile_domain': _get_val(host_rec, ["software_version", "cc_compile_domain"]), 'cc_compile_date': _get_val(host_rec, ["software_version", "cc_compile_date"]), 'xend_config_format': _get_val(host_rec, ["software_version", "xend_config_format"]) } return info
[ "def", "node_info", "(", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "# get node uuid", "host_rec", "=", "_get_record", "(", "xapi", ",", "'host'", ",", "_get_all", "(", "xapi", ",", "'host'", ")", "[", "0", "]", ")", "# get first...
Return a dict with information about this node CLI Example: .. code-block:: bash salt '*' virt.node_info
[ "Return", "a", "dict", "with", "information", "about", "this", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L268-L350
train
saltstack/salt
salt/modules/xapi_virt.py
get_nics
def get_nics(vm_): ''' Return info about the network interfaces of a named vm CLI Example: .. code-block:: bash salt '*' virt.get_nics <vm name> ''' with _get_xapi_session() as xapi: nic = {} vm_rec = _get_record_by_label(xapi, 'VM', vm_) if vm_rec is False: return False for vif in vm_rec['VIFs']: vif_rec = _get_record(xapi, 'VIF', vif) nic[vif_rec['MAC']] = { 'mac': vif_rec['MAC'], 'device': vif_rec['device'], 'mtu': vif_rec['MTU'] } return nic
python
def get_nics(vm_): ''' Return info about the network interfaces of a named vm CLI Example: .. code-block:: bash salt '*' virt.get_nics <vm name> ''' with _get_xapi_session() as xapi: nic = {} vm_rec = _get_record_by_label(xapi, 'VM', vm_) if vm_rec is False: return False for vif in vm_rec['VIFs']: vif_rec = _get_record(xapi, 'VIF', vif) nic[vif_rec['MAC']] = { 'mac': vif_rec['MAC'], 'device': vif_rec['device'], 'mtu': vif_rec['MTU'] } return nic
[ "def", "get_nics", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "nic", "=", "{", "}", "vm_rec", "=", "_get_record_by_label", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_rec", "is", "False", ":", "return", "...
Return info about the network interfaces of a named vm CLI Example: .. code-block:: bash salt '*' virt.get_nics <vm name>
[ "Return", "info", "about", "the", "network", "interfaces", "of", "a", "named", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L353-L377
train
saltstack/salt
salt/modules/xapi_virt.py
get_macs
def get_macs(vm_): ''' Return a list off MAC addresses from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_macs <vm name> ''' macs = [] nics = get_nics(vm_) if nics is None: return None for nic in nics: macs.append(nic) return macs
python
def get_macs(vm_): ''' Return a list off MAC addresses from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_macs <vm name> ''' macs = [] nics = get_nics(vm_) if nics is None: return None for nic in nics: macs.append(nic) return macs
[ "def", "get_macs", "(", "vm_", ")", ":", "macs", "=", "[", "]", "nics", "=", "get_nics", "(", "vm_", ")", "if", "nics", "is", "None", ":", "return", "None", "for", "nic", "in", "nics", ":", "macs", ".", "append", "(", "nic", ")", "return", "macs"...
Return a list off MAC addresses from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_macs <vm name>
[ "Return", "a", "list", "off", "MAC", "addresses", "from", "the", "named", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L380-L397
train
saltstack/salt
salt/modules/xapi_virt.py
get_disks
def get_disks(vm_): ''' Return the disks of a named vm CLI Example: .. code-block:: bash salt '*' virt.get_disks <vm name> ''' with _get_xapi_session() as xapi: disk = {} vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False for vbd in xapi.VM.get_VBDs(vm_uuid): dev = xapi.VBD.get_device(vbd) if not dev: continue prop = xapi.VBD.get_runtime_properties(vbd) disk[dev] = { 'backend': prop['backend'], 'type': prop['device-type'], 'protocol': prop['protocol'] } return disk
python
def get_disks(vm_): ''' Return the disks of a named vm CLI Example: .. code-block:: bash salt '*' virt.get_disks <vm name> ''' with _get_xapi_session() as xapi: disk = {} vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False for vbd in xapi.VM.get_VBDs(vm_uuid): dev = xapi.VBD.get_device(vbd) if not dev: continue prop = xapi.VBD.get_runtime_properties(vbd) disk[dev] = { 'backend': prop['backend'], 'type': prop['device-type'], 'protocol': prop['protocol'] } return disk
[ "def", "get_disks", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "disk", "=", "{", "}", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "F...
Return the disks of a named vm CLI Example: .. code-block:: bash salt '*' virt.get_disks <vm name>
[ "Return", "the", "disks", "of", "a", "named", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L400-L428
train
saltstack/salt
salt/modules/xapi_virt.py
setmem
def setmem(vm_, memory): ''' Changes the amount of memory allocated to VM. Memory is to be specified in MB CLI Example: .. code-block:: bash salt '*' virt.setmem myvm 768 ''' with _get_xapi_session() as xapi: mem_target = int(memory) * 1024 * 1024 vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.set_memory_dynamic_max_live(vm_uuid, mem_target) xapi.VM.set_memory_dynamic_min_live(vm_uuid, mem_target) return True except Exception: return False
python
def setmem(vm_, memory): ''' Changes the amount of memory allocated to VM. Memory is to be specified in MB CLI Example: .. code-block:: bash salt '*' virt.setmem myvm 768 ''' with _get_xapi_session() as xapi: mem_target = int(memory) * 1024 * 1024 vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.set_memory_dynamic_max_live(vm_uuid, mem_target) xapi.VM.set_memory_dynamic_min_live(vm_uuid, mem_target) return True except Exception: return False
[ "def", "setmem", "(", "vm_", ",", "memory", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "mem_target", "=", "int", "(", "memory", ")", "*", "1024", "*", "1024", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", ...
Changes the amount of memory allocated to VM. Memory is to be specified in MB CLI Example: .. code-block:: bash salt '*' virt.setmem myvm 768
[ "Changes", "the", "amount", "of", "memory", "allocated", "to", "VM", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L431-L454
train
saltstack/salt
salt/modules/xapi_virt.py
setvcpus
def setvcpus(vm_, vcpus): ''' Changes the amount of vcpus allocated to VM. vcpus is an int representing the number to be assigned CLI Example: .. code-block:: bash salt '*' virt.setvcpus myvm 2 ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.set_VCPUs_number_live(vm_uuid, vcpus) return True except Exception: return False
python
def setvcpus(vm_, vcpus): ''' Changes the amount of vcpus allocated to VM. vcpus is an int representing the number to be assigned CLI Example: .. code-block:: bash salt '*' virt.setvcpus myvm 2 ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.set_VCPUs_number_live(vm_uuid, vcpus) return True except Exception: return False
[ "def", "setvcpus", "(", "vm_", ",", "vcpus", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try"...
Changes the amount of vcpus allocated to VM. vcpus is an int representing the number to be assigned CLI Example: .. code-block:: bash salt '*' virt.setvcpus myvm 2
[ "Changes", "the", "amount", "of", "vcpus", "allocated", "to", "VM", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L457-L477
train
saltstack/salt
salt/modules/xapi_virt.py
vcpu_pin
def vcpu_pin(vm_, vcpu, cpus): ''' Set which CPUs a VCPU can use. CLI Example: .. code-block:: bash salt 'foo' virt.vcpu_pin domU-id 2 1 salt 'foo' virt.vcpu_pin domU-id 2 2-6 ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False # from xm's main def cpu_make_map(cpulist): cpus = [] for c in cpulist.split(','): if c == '': continue if '-' in c: (x, y) = c.split('-') for i in range(int(x), int(y) + 1): cpus.append(int(i)) else: # remove this element from the list if c[0] == '^': cpus = [x for x in cpus if x != int(c[1:])] else: cpus.append(int(c)) cpus.sort() return ','.join(map(str, cpus)) if cpus == 'all': cpumap = cpu_make_map('0-63') else: cpumap = cpu_make_map('{0}'.format(cpus)) try: xapi.VM.add_to_VCPUs_params_live(vm_uuid, 'cpumap{0}'.format(vcpu), cpumap) return True # VM.add_to_VCPUs_params_live() implementation in xend 4.1+ has # a bug which makes the client call fail. # That code is accurate for all others XenAPI implementations, but # for that particular one, fallback to xm / xl instead. except Exception: return __salt__['cmd.run']( '{0} vcpu-pin {1} {2} {3}'.format(_get_xtool(), vm_, vcpu, cpus), python_shell=False)
python
def vcpu_pin(vm_, vcpu, cpus): ''' Set which CPUs a VCPU can use. CLI Example: .. code-block:: bash salt 'foo' virt.vcpu_pin domU-id 2 1 salt 'foo' virt.vcpu_pin domU-id 2 2-6 ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False # from xm's main def cpu_make_map(cpulist): cpus = [] for c in cpulist.split(','): if c == '': continue if '-' in c: (x, y) = c.split('-') for i in range(int(x), int(y) + 1): cpus.append(int(i)) else: # remove this element from the list if c[0] == '^': cpus = [x for x in cpus if x != int(c[1:])] else: cpus.append(int(c)) cpus.sort() return ','.join(map(str, cpus)) if cpus == 'all': cpumap = cpu_make_map('0-63') else: cpumap = cpu_make_map('{0}'.format(cpus)) try: xapi.VM.add_to_VCPUs_params_live(vm_uuid, 'cpumap{0}'.format(vcpu), cpumap) return True # VM.add_to_VCPUs_params_live() implementation in xend 4.1+ has # a bug which makes the client call fail. # That code is accurate for all others XenAPI implementations, but # for that particular one, fallback to xm / xl instead. except Exception: return __salt__['cmd.run']( '{0} vcpu-pin {1} {2} {3}'.format(_get_xtool(), vm_, vcpu, cpus), python_shell=False)
[ "def", "vcpu_pin", "(", "vm_", ",", "vcpu", ",", "cpus", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", ...
Set which CPUs a VCPU can use. CLI Example: .. code-block:: bash salt 'foo' virt.vcpu_pin domU-id 2 1 salt 'foo' virt.vcpu_pin domU-id 2 2-6
[ "Set", "which", "CPUs", "a", "VCPU", "can", "use", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L480-L532
train
saltstack/salt
salt/modules/xapi_virt.py
shutdown
def shutdown(vm_): ''' Send a soft shutdown signal to the named vm CLI Example: .. code-block:: bash salt '*' virt.shutdown <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.clean_shutdown(vm_uuid) return True except Exception: return False
python
def shutdown(vm_): ''' Send a soft shutdown signal to the named vm CLI Example: .. code-block:: bash salt '*' virt.shutdown <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.clean_shutdown(vm_uuid) return True except Exception: return False
[ "def", "shutdown", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try", ":", "xapi",...
Send a soft shutdown signal to the named vm CLI Example: .. code-block:: bash salt '*' virt.shutdown <vm name>
[ "Send", "a", "soft", "shutdown", "signal", "to", "the", "named", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L576-L594
train
saltstack/salt
salt/modules/xapi_virt.py
pause
def pause(vm_): ''' Pause the named vm CLI Example: .. code-block:: bash salt '*' virt.pause <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.pause(vm_uuid) return True except Exception: return False
python
def pause(vm_): ''' Pause the named vm CLI Example: .. code-block:: bash salt '*' virt.pause <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.pause(vm_uuid) return True except Exception: return False
[ "def", "pause", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try", ":", "xapi", ...
Pause the named vm CLI Example: .. code-block:: bash salt '*' virt.pause <vm name>
[ "Pause", "the", "named", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L597-L615
train
saltstack/salt
salt/modules/xapi_virt.py
resume
def resume(vm_): ''' Resume the named vm CLI Example: .. code-block:: bash salt '*' virt.resume <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.unpause(vm_uuid) return True except Exception: return False
python
def resume(vm_): ''' Resume the named vm CLI Example: .. code-block:: bash salt '*' virt.resume <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.unpause(vm_uuid) return True except Exception: return False
[ "def", "resume", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try", ":", "xapi", ...
Resume the named vm CLI Example: .. code-block:: bash salt '*' virt.resume <vm name>
[ "Resume", "the", "named", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L618-L636
train
saltstack/salt
salt/modules/xapi_virt.py
reboot
def reboot(vm_): ''' Reboot a domain via ACPI request CLI Example: .. code-block:: bash salt '*' virt.reboot <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.clean_reboot(vm_uuid) return True except Exception: return False
python
def reboot(vm_): ''' Reboot a domain via ACPI request CLI Example: .. code-block:: bash salt '*' virt.reboot <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.clean_reboot(vm_uuid) return True except Exception: return False
[ "def", "reboot", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try", ":", "xapi", ...
Reboot a domain via ACPI request CLI Example: .. code-block:: bash salt '*' virt.reboot <vm name>
[ "Reboot", "a", "domain", "via", "ACPI", "request" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L656-L674
train
saltstack/salt
salt/modules/xapi_virt.py
reset
def reset(vm_): ''' Reset a VM by emulating the reset button on a physical machine CLI Example: .. code-block:: bash salt '*' virt.reset <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.hard_reboot(vm_uuid) return True except Exception: return False
python
def reset(vm_): ''' Reset a VM by emulating the reset button on a physical machine CLI Example: .. code-block:: bash salt '*' virt.reset <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.hard_reboot(vm_uuid) return True except Exception: return False
[ "def", "reset", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try", ":", "xapi", ...
Reset a VM by emulating the reset button on a physical machine CLI Example: .. code-block:: bash salt '*' virt.reset <vm name>
[ "Reset", "a", "VM", "by", "emulating", "the", "reset", "button", "on", "a", "physical", "machine" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L677-L695
train
saltstack/salt
salt/modules/xapi_virt.py
migrate
def migrate(vm_, target, live=1, port=0, node=-1, ssl=None, change_home_server=0): ''' Migrates the virtual machine to another hypervisor CLI Example: .. code-block:: bash salt '*' virt.migrate <vm name> <target hypervisor> [live] [port] [node] [ssl] [change_home_server] Optional values: live Use live migration port Use a specified port node Use specified NUMA node on target ssl use ssl connection for migration change_home_server change home server for managed domains ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False other_config = { 'port': port, 'node': node, 'ssl': ssl, 'change_home_server': change_home_server } try: xapi.VM.migrate(vm_uuid, target, bool(live), other_config) return True except Exception: return False
python
def migrate(vm_, target, live=1, port=0, node=-1, ssl=None, change_home_server=0): ''' Migrates the virtual machine to another hypervisor CLI Example: .. code-block:: bash salt '*' virt.migrate <vm name> <target hypervisor> [live] [port] [node] [ssl] [change_home_server] Optional values: live Use live migration port Use a specified port node Use specified NUMA node on target ssl use ssl connection for migration change_home_server change home server for managed domains ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False other_config = { 'port': port, 'node': node, 'ssl': ssl, 'change_home_server': change_home_server } try: xapi.VM.migrate(vm_uuid, target, bool(live), other_config) return True except Exception: return False
[ "def", "migrate", "(", "vm_", ",", "target", ",", "live", "=", "1", ",", "port", "=", "0", ",", "node", "=", "-", "1", ",", "ssl", "=", "None", ",", "change_home_server", "=", "0", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":...
Migrates the virtual machine to another hypervisor CLI Example: .. code-block:: bash salt '*' virt.migrate <vm name> <target hypervisor> [live] [port] [node] [ssl] [change_home_server] Optional values: live Use live migration port Use a specified port node Use specified NUMA node on target ssl use ssl connection for migration change_home_server change home server for managed domains
[ "Migrates", "the", "virtual", "machine", "to", "another", "hypervisor" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L698-L736
train
saltstack/salt
salt/modules/xapi_virt.py
stop
def stop(vm_): ''' Hard power down the virtual machine, this is equivalent to pulling the power CLI Example: .. code-block:: bash salt '*' virt.stop <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.hard_shutdown(vm_uuid) return True except Exception: return False
python
def stop(vm_): ''' Hard power down the virtual machine, this is equivalent to pulling the power CLI Example: .. code-block:: bash salt '*' virt.stop <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.hard_shutdown(vm_uuid) return True except Exception: return False
[ "def", "stop", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try", ":", "xapi", "...
Hard power down the virtual machine, this is equivalent to pulling the power CLI Example: .. code-block:: bash salt '*' virt.stop <vm name>
[ "Hard", "power", "down", "the", "virtual", "machine", "this", "is", "equivalent", "to", "pulling", "the", "power" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L739-L758
train
saltstack/salt
salt/modules/xapi_virt.py
is_hyper
def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): return False # there must be a smarter way... return 'xenstore' in __salt__['cmd.run'](__grains__['ps'])
python
def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): return False # there must be a smarter way... return 'xenstore' in __salt__['cmd.run'](__grains__['ps'])
[ "def", "is_hyper", "(", ")", ":", "try", ":", "if", "__grains__", "[", "'virtual_subtype'", "]", "!=", "'Xen Dom0'", ":", "return", "False", "except", "KeyError", ":", "# virtual_subtype isn't set everywhere.", "return", "False", "try", ":", "with", "salt", ".",...
Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper
[ "Returns", "a", "bool", "whether", "or", "not", "this", "node", "is", "a", "hypervisor", "of", "any", "kind" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L761-L784
train
saltstack/salt
salt/modules/xapi_virt.py
vm_cputime
def vm_cputime(vm_=None): ''' Return cputime used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' with _get_xapi_session() as xapi: def _info(vm_): host_rec = _get_record_by_label(xapi, 'VM', vm_) host_cpus = len(host_rec['host_CPUs']) if host_rec is False: return False host_metrics = _get_metrics_record(xapi, 'VM', host_rec) vcpus = int(host_metrics['VCPUs_number']) cputime = int(host_metrics['VCPUs_utilisation']['0']) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return {'cputime': int(cputime), 'cputime_percent': int('{0:.0f}'.format(cputime_percent))} info = {} if vm_: info[vm_] = _info(vm_) return info for vm_ in list_domains(): info[vm_] = _info(vm_) return info
python
def vm_cputime(vm_=None): ''' Return cputime used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' with _get_xapi_session() as xapi: def _info(vm_): host_rec = _get_record_by_label(xapi, 'VM', vm_) host_cpus = len(host_rec['host_CPUs']) if host_rec is False: return False host_metrics = _get_metrics_record(xapi, 'VM', host_rec) vcpus = int(host_metrics['VCPUs_number']) cputime = int(host_metrics['VCPUs_utilisation']['0']) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return {'cputime': int(cputime), 'cputime_percent': int('{0:.0f}'.format(cputime_percent))} info = {} if vm_: info[vm_] = _info(vm_) return info for vm_ in list_domains(): info[vm_] = _info(vm_) return info
[ "def", "vm_cputime", "(", "vm_", "=", "None", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "def", "_info", "(", "vm_", ")", ":", "host_rec", "=", "_get_record_by_label", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "host_cpus", "="...
Return cputime used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime
[ "Return", "cputime", "used", "by", "the", "vms", "on", "this", "hyper", "in", "a", "list", "of", "dicts", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L787-L834
train
saltstack/salt
salt/modules/xapi_virt.py
vm_netstats
def vm_netstats(vm_=None): ''' Return combined network counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_total_read_kbs' : 0, 'io_total_write_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' with _get_xapi_session() as xapi: def _info(vm_): ret = {} vm_rec = _get_record_by_label(xapi, 'VM', vm_) if vm_rec is False: return False for vif in vm_rec['VIFs']: vif_rec = _get_record(xapi, 'VIF', vif) ret[vif_rec['device']] = _get_metrics_record(xapi, 'VIF', vif_rec) del ret[vif_rec['device']]['last_updated'] return ret info = {} if vm_: info[vm_] = _info(vm_) else: for vm_ in list_domains(): info[vm_] = _info(vm_) return info
python
def vm_netstats(vm_=None): ''' Return combined network counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_total_read_kbs' : 0, 'io_total_write_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' with _get_xapi_session() as xapi: def _info(vm_): ret = {} vm_rec = _get_record_by_label(xapi, 'VM', vm_) if vm_rec is False: return False for vif in vm_rec['VIFs']: vif_rec = _get_record(xapi, 'VIF', vif) ret[vif_rec['device']] = _get_metrics_record(xapi, 'VIF', vif_rec) del ret[vif_rec['device']]['last_updated'] return ret info = {} if vm_: info[vm_] = _info(vm_) else: for vm_ in list_domains(): info[vm_] = _info(vm_) return info
[ "def", "vm_netstats", "(", "vm_", "=", "None", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "def", "_info", "(", "vm_", ")", ":", "ret", "=", "{", "}", "vm_rec", "=", "_get_record_by_label", "(", "xapi", ",", "'VM'", ",", "vm_"...
Return combined network counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_total_read_kbs' : 0, 'io_total_write_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats
[ "Return", "combined", "network", "counters", "used", "by", "the", "vms", "on", "this", "hyper", "in", "a", "list", "of", "dicts", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L837-L883
train
saltstack/salt
salt/modules/xapi_virt.py
vm_diskstats
def vm_diskstats(vm_=None): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_diskstats ''' with _get_xapi_session() as xapi: def _info(vm_): ret = {} vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False for vbd in xapi.VM.get_VBDs(vm_uuid): vbd_rec = _get_record(xapi, 'VBD', vbd) ret[vbd_rec['device']] = _get_metrics_record(xapi, 'VBD', vbd_rec) del ret[vbd_rec['device']]['last_updated'] return ret info = {} if vm_: info[vm_] = _info(vm_) else: for vm_ in list_domains(): info[vm_] = _info(vm_) return info
python
def vm_diskstats(vm_=None): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_diskstats ''' with _get_xapi_session() as xapi: def _info(vm_): ret = {} vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False for vbd in xapi.VM.get_VBDs(vm_uuid): vbd_rec = _get_record(xapi, 'VBD', vbd) ret[vbd_rec['device']] = _get_metrics_record(xapi, 'VBD', vbd_rec) del ret[vbd_rec['device']]['last_updated'] return ret info = {} if vm_: info[vm_] = _info(vm_) else: for vm_ in list_domains(): info[vm_] = _info(vm_) return info
[ "def", "vm_diskstats", "(", "vm_", "=", "None", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "def", "_info", "(", "vm_", ")", ":", "ret", "=", "{", "}", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ...
Return disk usage counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_diskstats
[ "Return", "disk", "usage", "counters", "used", "by", "the", "vms", "on", "this", "hyper", "in", "a", "list", "of", "dicts", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L886-L930
train
saltstack/salt
salt/modules/zonecfg.py
_clean_message
def _clean_message(message): '''Internal helper to sanitize message output''' message = message.replace('zonecfg: ', '') message = message.splitlines() for line in message: if line.startswith('On line'): message.remove(line) return "\n".join(message)
python
def _clean_message(message): '''Internal helper to sanitize message output''' message = message.replace('zonecfg: ', '') message = message.splitlines() for line in message: if line.startswith('On line'): message.remove(line) return "\n".join(message)
[ "def", "_clean_message", "(", "message", ")", ":", "message", "=", "message", ".", "replace", "(", "'zonecfg: '", ",", "''", ")", "message", "=", "message", ".", "splitlines", "(", ")", "for", "line", "in", "message", ":", "if", "line", ".", "startswith"...
Internal helper to sanitize message output
[ "Internal", "helper", "to", "sanitize", "message", "output" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L117-L124
train
saltstack/salt
salt/modules/zonecfg.py
_parse_value
def _parse_value(value): '''Internal helper for parsing configuration values into python values''' if isinstance(value, bool): return 'true' if value else 'false' elif isinstance(value, six.string_types): # parse compacted notation to dict listparser = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''') value = value.strip() if value.startswith('[') and value.endswith(']'): return listparser.split(value[1:-1])[1::2] elif value.startswith('(') and value.endswith(')'): rval = {} for pair in listparser.split(value[1:-1])[1::2]: pair = pair.split('=') if '"' in pair[1]: pair[1] = pair[1].replace('"', '') if pair[1].isdigit(): rval[pair[0]] = int(pair[1]) elif pair[1] == 'true': rval[pair[0]] = True elif pair[1] == 'false': rval[pair[0]] = False else: rval[pair[0]] = pair[1] return rval else: if '"' in value: value = value.replace('"', '') if value.isdigit(): return int(value) elif value == 'true': return True elif value == 'false': return False else: return value else: return value
python
def _parse_value(value): '''Internal helper for parsing configuration values into python values''' if isinstance(value, bool): return 'true' if value else 'false' elif isinstance(value, six.string_types): # parse compacted notation to dict listparser = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''') value = value.strip() if value.startswith('[') and value.endswith(']'): return listparser.split(value[1:-1])[1::2] elif value.startswith('(') and value.endswith(')'): rval = {} for pair in listparser.split(value[1:-1])[1::2]: pair = pair.split('=') if '"' in pair[1]: pair[1] = pair[1].replace('"', '') if pair[1].isdigit(): rval[pair[0]] = int(pair[1]) elif pair[1] == 'true': rval[pair[0]] = True elif pair[1] == 'false': rval[pair[0]] = False else: rval[pair[0]] = pair[1] return rval else: if '"' in value: value = value.replace('"', '') if value.isdigit(): return int(value) elif value == 'true': return True elif value == 'false': return False else: return value else: return value
[ "def", "_parse_value", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "'true'", "if", "value", "else", "'false'", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "# parse compacted ...
Internal helper for parsing configuration values into python values
[ "Internal", "helper", "for", "parsing", "configuration", "values", "into", "python", "values" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L127-L165
train
saltstack/salt
salt/modules/zonecfg.py
_sanitize_value
def _sanitize_value(value): '''Internal helper for converting pythonic values to configuration file values''' # dump dict into compated if isinstance(value, dict): new_value = [] new_value.append('(') for k, v in value.items(): new_value.append(k) new_value.append('=') new_value.append(v) new_value.append(',') new_value.append(')') return "".join(six.text_type(v) for v in new_value).replace(',)', ')') elif isinstance(value, list): new_value = [] new_value.append('(') for item in value: if isinstance(item, OrderedDict): item = dict(item) for k, v in item.items(): new_value.append(k) new_value.append('=') new_value.append(v) else: new_value.append(item) new_value.append(',') new_value.append(')') return "".join(six.text_type(v) for v in new_value).replace(',)', ')') else: # note: we can't use shelx or pipes quote here because it makes zonecfg barf return '"{0}"'.format(value) if ' ' in value else value
python
def _sanitize_value(value): '''Internal helper for converting pythonic values to configuration file values''' # dump dict into compated if isinstance(value, dict): new_value = [] new_value.append('(') for k, v in value.items(): new_value.append(k) new_value.append('=') new_value.append(v) new_value.append(',') new_value.append(')') return "".join(six.text_type(v) for v in new_value).replace(',)', ')') elif isinstance(value, list): new_value = [] new_value.append('(') for item in value: if isinstance(item, OrderedDict): item = dict(item) for k, v in item.items(): new_value.append(k) new_value.append('=') new_value.append(v) else: new_value.append(item) new_value.append(',') new_value.append(')') return "".join(six.text_type(v) for v in new_value).replace(',)', ')') else: # note: we can't use shelx or pipes quote here because it makes zonecfg barf return '"{0}"'.format(value) if ' ' in value else value
[ "def", "_sanitize_value", "(", "value", ")", ":", "# dump dict into compated", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "new_value", "=", "[", "]", "new_value", ".", "append", "(", "'('", ")", "for", "k", ",", "v", "in", "value", ".", "...
Internal helper for converting pythonic values to configuration file values
[ "Internal", "helper", "for", "converting", "pythonic", "values", "to", "configuration", "file", "values" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L168-L198
train
saltstack/salt
salt/modules/zonecfg.py
_dump_cfg
def _dump_cfg(cfg_file): '''Internal helper for debugging cfg files''' if __salt__['file.file_exists'](cfg_file): with salt.utils.files.fopen(cfg_file, 'r') as fp_: log.debug( "zonecfg - configuration file:\n%s", "".join(salt.utils.data.decode(fp_.readlines())) )
python
def _dump_cfg(cfg_file): '''Internal helper for debugging cfg files''' if __salt__['file.file_exists'](cfg_file): with salt.utils.files.fopen(cfg_file, 'r') as fp_: log.debug( "zonecfg - configuration file:\n%s", "".join(salt.utils.data.decode(fp_.readlines())) )
[ "def", "_dump_cfg", "(", "cfg_file", ")", ":", "if", "__salt__", "[", "'file.file_exists'", "]", "(", "cfg_file", ")", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "cfg_file", ",", "'r'", ")", "as", "fp_", ":", "log", ".", "deb...
Internal helper for debugging cfg files
[ "Internal", "helper", "for", "debugging", "cfg", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L201-L208
train
saltstack/salt
salt/modules/zonecfg.py
create
def create(zone, brand, zonepath, force=False): ''' Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: .. code-block:: bash salt '*' zonecfg.create deathscythe ipkg /zones/deathscythe ''' ret = {'status': True} # write config cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: fp_.write("create -b -F\n" if force else "create -b\n") fp_.write("set brand={0}\n".format(_sanitize_value(brand))) fp_.write("set zonepath={0}\n".format(_sanitize_value(zonepath))) # create if not __salt__['file.directory_exists'](zonepath): __salt__['file.makedirs_perms'](zonepath if zonepath[-1] == '/' else '{0}/'.format(zonepath), mode='0700') _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {cfg}'.format( zone=zone, cfg=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
python
def create(zone, brand, zonepath, force=False): ''' Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: .. code-block:: bash salt '*' zonecfg.create deathscythe ipkg /zones/deathscythe ''' ret = {'status': True} # write config cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: fp_.write("create -b -F\n" if force else "create -b\n") fp_.write("set brand={0}\n".format(_sanitize_value(brand))) fp_.write("set zonepath={0}\n".format(_sanitize_value(zonepath))) # create if not __salt__['file.directory_exists'](zonepath): __salt__['file.makedirs_perms'](zonepath if zonepath[-1] == '/' else '{0}/'.format(zonepath), mode='0700') _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {cfg}'.format( zone=zone, cfg=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
[ "def", "create", "(", "zone", ",", "brand", ",", "zonepath", ",", "force", "=", "False", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# write config", "cfg_file", "=", "salt", ".", "utils", ".", "files", ".", "mkstemp", "(", ")", "with",...
Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: .. code-block:: bash salt '*' zonecfg.create deathscythe ipkg /zones/deathscythe
[ "Create", "an", "in", "-", "memory", "configuration", "for", "the", "specified", "zone", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L211-L259
train
saltstack/salt
salt/modules/zonecfg.py
create_from_template
def create_from_template(zone, template): ''' Create an in-memory configuration from a template for the specified zone. zone : string name of zone template : string name of template .. warning:: existing config will be overwritten! CLI Example: .. code-block:: bash salt '*' zonecfg.create_from_template leo tallgeese ''' ret = {'status': True} # create from template _dump_cfg(template) res = __salt__['cmd.run_all']('zonecfg -z {zone} create -t {tmpl} -F'.format( zone=zone, tmpl=template, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) return ret
python
def create_from_template(zone, template): ''' Create an in-memory configuration from a template for the specified zone. zone : string name of zone template : string name of template .. warning:: existing config will be overwritten! CLI Example: .. code-block:: bash salt '*' zonecfg.create_from_template leo tallgeese ''' ret = {'status': True} # create from template _dump_cfg(template) res = __salt__['cmd.run_all']('zonecfg -z {zone} create -t {tmpl} -F'.format( zone=zone, tmpl=template, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) return ret
[ "def", "create_from_template", "(", "zone", ",", "template", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# create from template", "_dump_cfg", "(", "template", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'zonecfg -z {zone} create ...
Create an in-memory configuration from a template for the specified zone. zone : string name of zone template : string name of template .. warning:: existing config will be overwritten! CLI Example: .. code-block:: bash salt '*' zonecfg.create_from_template leo tallgeese
[ "Create", "an", "in", "-", "memory", "configuration", "from", "a", "template", "for", "the", "specified", "zone", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L262-L295
train
saltstack/salt
salt/modules/zonecfg.py
delete
def delete(zone): ''' Delete the specified configuration from memory and stable storage. zone : string name of zone CLI Example: .. code-block:: bash salt '*' zonecfg.delete epyon ''' ret = {'status': True} # delete zone res = __salt__['cmd.run_all']('zonecfg -z {zone} delete -F'.format( zone=zone, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) return ret
python
def delete(zone): ''' Delete the specified configuration from memory and stable storage. zone : string name of zone CLI Example: .. code-block:: bash salt '*' zonecfg.delete epyon ''' ret = {'status': True} # delete zone res = __salt__['cmd.run_all']('zonecfg -z {zone} delete -F'.format( zone=zone, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) return ret
[ "def", "delete", "(", "zone", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# delete zone", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'zonecfg -z {zone} delete -F'", ".", "format", "(", "zone", "=", "zone", ",", ")", ")", "ret"...
Delete the specified configuration from memory and stable storage. zone : string name of zone CLI Example: .. code-block:: bash salt '*' zonecfg.delete epyon
[ "Delete", "the", "specified", "configuration", "from", "memory", "and", "stable", "storage", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L298-L324
train
saltstack/salt
salt/modules/zonecfg.py
export
def export(zone, path=None): ''' Export the configuration from memory to stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.export epyon salt '*' zonecfg.export epyon /zones/epyon.cfg ''' ret = {'status': True} # export zone res = __salt__['cmd.run_all']('zonecfg -z {zone} export{path}'.format( zone=zone, path=' -f {0}'.format(path) if path else '', )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) return ret
python
def export(zone, path=None): ''' Export the configuration from memory to stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.export epyon salt '*' zonecfg.export epyon /zones/epyon.cfg ''' ret = {'status': True} # export zone res = __salt__['cmd.run_all']('zonecfg -z {zone} export{path}'.format( zone=zone, path=' -f {0}'.format(path) if path else '', )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) return ret
[ "def", "export", "(", "zone", ",", "path", "=", "None", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# export zone", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'zonecfg -z {zone} export{path}'", ".", "format", "(", "zone", "=", ...
Export the configuration from memory to stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.export epyon salt '*' zonecfg.export epyon /zones/epyon.cfg
[ "Export", "the", "configuration", "from", "memory", "to", "stable", "storage", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L327-L357
train
saltstack/salt
salt/modules/zonecfg.py
import_
def import_(zone, path): ''' Import the configuration to memory from stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.import epyon /zones/epyon.cfg ''' ret = {'status': True} # create from file _dump_cfg(path) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=path, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) return ret
python
def import_(zone, path): ''' Import the configuration to memory from stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.import epyon /zones/epyon.cfg ''' ret = {'status': True} # create from file _dump_cfg(path) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=path, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) return ret
[ "def", "import_", "(", "zone", ",", "path", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# create from file", "_dump_cfg", "(", "path", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'zonecfg -z {zone} -f {path}'", ".", "format", ...
Import the configuration to memory from stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.import epyon /zones/epyon.cfg
[ "Import", "the", "configuration", "to", "memory", "from", "stable", "storage", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L360-L390
train
saltstack/salt
salt/modules/zonecfg.py
_property
def _property(methode, zone, key, value): ''' internal handler for set and clear_property methode : string either set, add, or clear zone : string name of zone key : string name of property value : string value of property ''' ret = {'status': True} # generate update script cfg_file = None if methode not in ['set', 'clear']: ret['status'] = False ret['message'] = 'unkown methode {0}!'.format(methode) else: cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: if methode == 'set': if isinstance(value, dict) or isinstance(value, list): value = _sanitize_value(value) value = six.text_type(value).lower() if isinstance(value, bool) else six.text_type(value) fp_.write("{0} {1}={2}\n".format(methode, key, _sanitize_value(value))) elif methode == 'clear': fp_.write("{0} {1}\n".format(methode, key)) # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
python
def _property(methode, zone, key, value): ''' internal handler for set and clear_property methode : string either set, add, or clear zone : string name of zone key : string name of property value : string value of property ''' ret = {'status': True} # generate update script cfg_file = None if methode not in ['set', 'clear']: ret['status'] = False ret['message'] = 'unkown methode {0}!'.format(methode) else: cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: if methode == 'set': if isinstance(value, dict) or isinstance(value, list): value = _sanitize_value(value) value = six.text_type(value).lower() if isinstance(value, bool) else six.text_type(value) fp_.write("{0} {1}={2}\n".format(methode, key, _sanitize_value(value))) elif methode == 'clear': fp_.write("{0} {1}\n".format(methode, key)) # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
[ "def", "_property", "(", "methode", ",", "zone", ",", "key", ",", "value", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# generate update script", "cfg_file", "=", "None", "if", "methode", "not", "in", "[", "'set'", ",", "'clear'", "]", ":...
internal handler for set and clear_property methode : string either set, add, or clear zone : string name of zone key : string name of property value : string value of property
[ "internal", "handler", "for", "set", "and", "clear_property" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L393-L443
train
saltstack/salt
salt/modules/zonecfg.py
_resource
def _resource(methode, zone, resource_type, resource_selector, **kwargs): ''' internal resource hanlder methode : string add or update zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier **kwargs : string|int|... resource properties ''' ret = {'status': True} # parse kwargs kwargs = salt.utils.args.clean_kwargs(**kwargs) for k in kwargs: if isinstance(kwargs[k], dict) or isinstance(kwargs[k], list): kwargs[k] = _sanitize_value(kwargs[k]) if methode not in ['add', 'update']: ret['status'] = False ret['message'] = 'unknown methode {0}'.format(methode) return ret if methode in ['update'] and resource_selector and resource_selector not in kwargs: ret['status'] = False ret['message'] = 'resource selector {0} not found in parameters'.format(resource_selector) return ret # generate update script cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: if methode in ['add']: fp_.write("add {0}\n".format(resource_type)) elif methode in ['update']: if resource_selector: value = kwargs[resource_selector] if isinstance(value, dict) or isinstance(value, list): value = _sanitize_value(value) value = six.text_type(value).lower() if isinstance(value, bool) else six.text_type(value) fp_.write("select {0} {1}={2}\n".format(resource_type, resource_selector, _sanitize_value(value))) else: fp_.write("select {0}\n".format(resource_type)) for k, v in six.iteritems(kwargs): if methode in ['update'] and k == resource_selector: continue if isinstance(v, dict) or isinstance(v, list): value = _sanitize_value(value) value = six.text_type(v).lower() if isinstance(v, bool) else six.text_type(v) if k in _zonecfg_resource_setters[resource_type]: fp_.write("set {0}={1}\n".format(k, _sanitize_value(value))) else: fp_.write("add {0} {1}\n".format(k, _sanitize_value(value))) fp_.write("end\n") # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
python
def _resource(methode, zone, resource_type, resource_selector, **kwargs): ''' internal resource hanlder methode : string add or update zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier **kwargs : string|int|... resource properties ''' ret = {'status': True} # parse kwargs kwargs = salt.utils.args.clean_kwargs(**kwargs) for k in kwargs: if isinstance(kwargs[k], dict) or isinstance(kwargs[k], list): kwargs[k] = _sanitize_value(kwargs[k]) if methode not in ['add', 'update']: ret['status'] = False ret['message'] = 'unknown methode {0}'.format(methode) return ret if methode in ['update'] and resource_selector and resource_selector not in kwargs: ret['status'] = False ret['message'] = 'resource selector {0} not found in parameters'.format(resource_selector) return ret # generate update script cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: if methode in ['add']: fp_.write("add {0}\n".format(resource_type)) elif methode in ['update']: if resource_selector: value = kwargs[resource_selector] if isinstance(value, dict) or isinstance(value, list): value = _sanitize_value(value) value = six.text_type(value).lower() if isinstance(value, bool) else six.text_type(value) fp_.write("select {0} {1}={2}\n".format(resource_type, resource_selector, _sanitize_value(value))) else: fp_.write("select {0}\n".format(resource_type)) for k, v in six.iteritems(kwargs): if methode in ['update'] and k == resource_selector: continue if isinstance(v, dict) or isinstance(v, list): value = _sanitize_value(value) value = six.text_type(v).lower() if isinstance(v, bool) else six.text_type(v) if k in _zonecfg_resource_setters[resource_type]: fp_.write("set {0}={1}\n".format(k, _sanitize_value(value))) else: fp_.write("add {0} {1}\n".format(k, _sanitize_value(value))) fp_.write("end\n") # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
[ "def", "_resource", "(", "methode", ",", "zone", ",", "resource_type", ",", "resource_selector", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# parse kwargs", "kwargs", "=", "salt", ".", "utils", ".", "args", ".", ...
internal resource hanlder methode : string add or update zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier **kwargs : string|int|... resource properties
[ "internal", "resource", "hanlder" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L494-L570
train
saltstack/salt
salt/modules/zonecfg.py
update_resource
def update_resource(zone, resource_type, resource_selector, **kwargs): ''' Add a resource zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier kwargs : string|int|... resource properties .. note:: Set resource_selector to None for resource that do not require one. CLI Example: .. code-block:: bash salt '*' zonecfg.update_resource tallgeese rctl name name=zone.max-locked-memory value='(priv=privileged,limit=33554432,action=deny)' ''' return _resource('update', zone, resource_type, resource_selector, **kwargs)
python
def update_resource(zone, resource_type, resource_selector, **kwargs): ''' Add a resource zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier kwargs : string|int|... resource properties .. note:: Set resource_selector to None for resource that do not require one. CLI Example: .. code-block:: bash salt '*' zonecfg.update_resource tallgeese rctl name name=zone.max-locked-memory value='(priv=privileged,limit=33554432,action=deny)' ''' return _resource('update', zone, resource_type, resource_selector, **kwargs)
[ "def", "update_resource", "(", "zone", ",", "resource_type", ",", "resource_selector", ",", "*", "*", "kwargs", ")", ":", "return", "_resource", "(", "'update'", ",", "zone", ",", "resource_type", ",", "resource_selector", ",", "*", "*", "kwargs", ")" ]
Add a resource zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier kwargs : string|int|... resource properties .. note:: Set resource_selector to None for resource that do not require one. CLI Example: .. code-block:: bash salt '*' zonecfg.update_resource tallgeese rctl name name=zone.max-locked-memory value='(priv=privileged,limit=33554432,action=deny)'
[ "Add", "a", "resource" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L593-L615
train
saltstack/salt
salt/modules/zonecfg.py
remove_resource
def remove_resource(zone, resource_type, resource_key, resource_value): ''' Remove a resource zone : string name of zone resource_type : string type of resource resource_key : string key for resource selection resource_value : string value for resource selection .. note:: Set resource_selector to None for resource that do not require one. CLI Example: .. code-block:: bash salt '*' zonecfg.remove_resource tallgeese rctl name zone.max-locked-memory ''' ret = {'status': True} # generate update script cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: if resource_key: fp_.write("remove {0} {1}={2}\n".format(resource_type, resource_key, _sanitize_value(resource_value))) else: fp_.write("remove {0}\n".format(resource_type)) # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
python
def remove_resource(zone, resource_type, resource_key, resource_value): ''' Remove a resource zone : string name of zone resource_type : string type of resource resource_key : string key for resource selection resource_value : string value for resource selection .. note:: Set resource_selector to None for resource that do not require one. CLI Example: .. code-block:: bash salt '*' zonecfg.remove_resource tallgeese rctl name zone.max-locked-memory ''' ret = {'status': True} # generate update script cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: if resource_key: fp_.write("remove {0} {1}={2}\n".format(resource_type, resource_key, _sanitize_value(resource_value))) else: fp_.write("remove {0}\n".format(resource_type)) # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
[ "def", "remove_resource", "(", "zone", ",", "resource_type", ",", "resource_key", ",", "resource_value", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# generate update script", "cfg_file", "=", "salt", ".", "utils", ".", "files", ".", "mkstemp", ...
Remove a resource zone : string name of zone resource_type : string type of resource resource_key : string key for resource selection resource_value : string value for resource selection .. note:: Set resource_selector to None for resource that do not require one. CLI Example: .. code-block:: bash salt '*' zonecfg.remove_resource tallgeese rctl name zone.max-locked-memory
[ "Remove", "a", "resource" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L618-L668
train
saltstack/salt
salt/modules/zonecfg.py
info
def info(zone, show_all=False): ''' Display the configuration from memory zone : string name of zone show_all : boolean also include calculated values like capped-cpu, cpu-shares, ... CLI Example: .. code-block:: bash salt '*' zonecfg.info tallgeese ''' ret = {} # dump zone res = __salt__['cmd.run_all']('zonecfg -z {zone} info'.format( zone=zone, )) if res['retcode'] == 0: # parse output resname = None resdata = {} for line in res['stdout'].split("\n"): # skip some bad data if ':' not in line: continue # skip calculated values (if requested) if line.startswith('['): if not show_all: continue line = line.rstrip()[1:-1] # extract key key = line.strip().split(':')[0] if '[' in key: key = key[1:] # parse calculated resource (if requested) if key in _zonecfg_info_resources_calculated: if resname: ret[resname].append(resdata) if show_all: resname = key resdata = {} if key not in ret: ret[key] = [] else: resname = None resdata = {} # parse resources elif key in _zonecfg_info_resources: if resname: ret[resname].append(resdata) resname = key resdata = {} if key not in ret: ret[key] = [] # store resource property elif line.startswith("\t"): # ship calculated values (if requested) if line.strip().startswith('['): if not show_all: continue line = line.strip()[1:-1] if key == 'property': # handle special 'property' keys if 'property' not in resdata: resdata[key] = {} kv = _parse_value(line.strip()[line.strip().index(':')+1:]) if 'name' in kv and 'value' in kv: resdata[key][kv['name']] = kv['value'] else: log.warning('zonecfg.info - not sure how to deal with: %s', kv) else: resdata[key] = _parse_value(line.strip()[line.strip().index(':')+1:]) # store property else: if resname: ret[resname].append(resdata) resname = None resdata = {} if key == 'property': # handle special 'property' keys if 'property' not in ret: ret[key] = {} kv = _parse_value(line.strip()[line.strip().index(':')+1:]) if 'name' in kv and 'value' in kv: res[key][kv['name']] = kv['value'] else: log.warning('zonecfg.info - not sure how to deal with: %s', kv) else: ret[key] = _parse_value(line.strip()[line.strip().index(':')+1:]) # store hanging resource if resname: ret[resname].append(resdata) return ret
python
def info(zone, show_all=False): ''' Display the configuration from memory zone : string name of zone show_all : boolean also include calculated values like capped-cpu, cpu-shares, ... CLI Example: .. code-block:: bash salt '*' zonecfg.info tallgeese ''' ret = {} # dump zone res = __salt__['cmd.run_all']('zonecfg -z {zone} info'.format( zone=zone, )) if res['retcode'] == 0: # parse output resname = None resdata = {} for line in res['stdout'].split("\n"): # skip some bad data if ':' not in line: continue # skip calculated values (if requested) if line.startswith('['): if not show_all: continue line = line.rstrip()[1:-1] # extract key key = line.strip().split(':')[0] if '[' in key: key = key[1:] # parse calculated resource (if requested) if key in _zonecfg_info_resources_calculated: if resname: ret[resname].append(resdata) if show_all: resname = key resdata = {} if key not in ret: ret[key] = [] else: resname = None resdata = {} # parse resources elif key in _zonecfg_info_resources: if resname: ret[resname].append(resdata) resname = key resdata = {} if key not in ret: ret[key] = [] # store resource property elif line.startswith("\t"): # ship calculated values (if requested) if line.strip().startswith('['): if not show_all: continue line = line.strip()[1:-1] if key == 'property': # handle special 'property' keys if 'property' not in resdata: resdata[key] = {} kv = _parse_value(line.strip()[line.strip().index(':')+1:]) if 'name' in kv and 'value' in kv: resdata[key][kv['name']] = kv['value'] else: log.warning('zonecfg.info - not sure how to deal with: %s', kv) else: resdata[key] = _parse_value(line.strip()[line.strip().index(':')+1:]) # store property else: if resname: ret[resname].append(resdata) resname = None resdata = {} if key == 'property': # handle special 'property' keys if 'property' not in ret: ret[key] = {} kv = _parse_value(line.strip()[line.strip().index(':')+1:]) if 'name' in kv and 'value' in kv: res[key][kv['name']] = kv['value'] else: log.warning('zonecfg.info - not sure how to deal with: %s', kv) else: ret[key] = _parse_value(line.strip()[line.strip().index(':')+1:]) # store hanging resource if resname: ret[resname].append(resdata) return ret
[ "def", "info", "(", "zone", ",", "show_all", "=", "False", ")", ":", "ret", "=", "{", "}", "# dump zone", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'zonecfg -z {zone} info'", ".", "format", "(", "zone", "=", "zone", ",", ")", ")", "if", ...
Display the configuration from memory zone : string name of zone show_all : boolean also include calculated values like capped-cpu, cpu-shares, ... CLI Example: .. code-block:: bash salt '*' zonecfg.info tallgeese
[ "Display", "the", "configuration", "from", "memory" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L671-L769
train
saltstack/salt
salt/cli/daemons.py
DaemonsMixin.verify_hash_type
def verify_hash_type(self): ''' Verify and display a nag-messsage to the log if vulnerable hash-type is used. :return: ''' if self.config['hash_type'].lower() in ['md5', 'sha1']: log.warning( 'IMPORTANT: Do not use %s hashing algorithm! Please set ' '"hash_type" to sha256 in Salt %s config!', self.config['hash_type'], self.__class__.__name__ )
python
def verify_hash_type(self): ''' Verify and display a nag-messsage to the log if vulnerable hash-type is used. :return: ''' if self.config['hash_type'].lower() in ['md5', 'sha1']: log.warning( 'IMPORTANT: Do not use %s hashing algorithm! Please set ' '"hash_type" to sha256 in Salt %s config!', self.config['hash_type'], self.__class__.__name__ )
[ "def", "verify_hash_type", "(", "self", ")", ":", "if", "self", ".", "config", "[", "'hash_type'", "]", ".", "lower", "(", ")", "in", "[", "'md5'", ",", "'sha1'", "]", ":", "log", ".", "warning", "(", "'IMPORTANT: Do not use %s hashing algorithm! Please set '"...
Verify and display a nag-messsage to the log if vulnerable hash-type is used. :return:
[ "Verify", "and", "display", "a", "nag", "-", "messsage", "to", "the", "log", "if", "vulnerable", "hash", "-", "type", "is", "used", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L65-L76
train
saltstack/salt
salt/cli/daemons.py
DaemonsMixin.environment_failure
def environment_failure(self, error): ''' Log environment failure for the daemon and exit with the error code. :param error: :return: ''' log.exception( 'Failed to create environment for %s: %s', self.__class__.__name__, get_error_message(error) ) self.shutdown(error)
python
def environment_failure(self, error): ''' Log environment failure for the daemon and exit with the error code. :param error: :return: ''' log.exception( 'Failed to create environment for %s: %s', self.__class__.__name__, get_error_message(error) ) self.shutdown(error)
[ "def", "environment_failure", "(", "self", ",", "error", ")", ":", "log", ".", "exception", "(", "'Failed to create environment for %s: %s'", ",", "self", ".", "__class__", ".", "__name__", ",", "get_error_message", "(", "error", ")", ")", "self", ".", "shutdown...
Log environment failure for the daemon and exit with the error code. :param error: :return:
[ "Log", "environment", "failure", "for", "the", "daemon", "and", "exit", "with", "the", "error", "code", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L103-L114
train
saltstack/salt
salt/cli/daemons.py
Master.prepare
def prepare(self): ''' Run the preparation sequence required to start a salt master server. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Master, self).prepare() try: if self.config['verify_env']: v_dirs = [ self.config['pki_dir'], os.path.join(self.config['pki_dir'], 'minions'), os.path.join(self.config['pki_dir'], 'minions_pre'), os.path.join(self.config['pki_dir'], 'minions_denied'), os.path.join(self.config['pki_dir'], 'minions_autosign'), os.path.join(self.config['pki_dir'], 'minions_rejected'), self.config['cachedir'], os.path.join(self.config['cachedir'], 'jobs'), os.path.join(self.config['cachedir'], 'proc'), self.config['sock_dir'], self.config['token_dir'], self.config['syndic_dir'], self.config['sqlite_queue_dir'], ] verify_env( v_dirs, self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) # Clear out syndics from cachedir for syndic_file in os.listdir(self.config['syndic_dir']): os.remove(os.path.join(self.config['syndic_dir'], syndic_file)) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) self.action_log_info('Setting up') # TODO: AIO core is separate from transport if not verify_socket(self.config['interface'], self.config['publish_port'], self.config['ret_port']): self.shutdown(4, 'The ports are not available to bind') self.config['interface'] = ip_bracket(self.config['interface']) migrations.migrate_paths(self.config) # Late import so logging works correctly import salt.master self.master = salt.master.Master(self.config) self.daemonize_if_required() self.set_pidfile() salt.utils.process.notify_systemd()
python
def prepare(self): ''' Run the preparation sequence required to start a salt master server. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Master, self).prepare() try: if self.config['verify_env']: v_dirs = [ self.config['pki_dir'], os.path.join(self.config['pki_dir'], 'minions'), os.path.join(self.config['pki_dir'], 'minions_pre'), os.path.join(self.config['pki_dir'], 'minions_denied'), os.path.join(self.config['pki_dir'], 'minions_autosign'), os.path.join(self.config['pki_dir'], 'minions_rejected'), self.config['cachedir'], os.path.join(self.config['cachedir'], 'jobs'), os.path.join(self.config['cachedir'], 'proc'), self.config['sock_dir'], self.config['token_dir'], self.config['syndic_dir'], self.config['sqlite_queue_dir'], ] verify_env( v_dirs, self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) # Clear out syndics from cachedir for syndic_file in os.listdir(self.config['syndic_dir']): os.remove(os.path.join(self.config['syndic_dir'], syndic_file)) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) self.action_log_info('Setting up') # TODO: AIO core is separate from transport if not verify_socket(self.config['interface'], self.config['publish_port'], self.config['ret_port']): self.shutdown(4, 'The ports are not available to bind') self.config['interface'] = ip_bracket(self.config['interface']) migrations.migrate_paths(self.config) # Late import so logging works correctly import salt.master self.master = salt.master.Master(self.config) self.daemonize_if_required() self.set_pidfile() salt.utils.process.notify_systemd()
[ "def", "prepare", "(", "self", ")", ":", "super", "(", "Master", ",", "self", ")", ".", "prepare", "(", ")", "try", ":", "if", "self", ".", "config", "[", "'verify_env'", "]", ":", "v_dirs", "=", "[", "self", ".", "config", "[", "'pki_dir'", "]", ...
Run the preparation sequence required to start a salt master server. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare()
[ "Run", "the", "preparation", "sequence", "required", "to", "start", "a", "salt", "master", "server", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L130-L190
train
saltstack/salt
salt/cli/daemons.py
Master.start
def start(self): ''' Start the actual master. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Master, self).start() if check_user(self.config['user']): self.action_log_info('Starting up') self.verify_hash_type() self.master.start()
python
def start(self): ''' Start the actual master. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Master, self).start() if check_user(self.config['user']): self.action_log_info('Starting up') self.verify_hash_type() self.master.start()
[ "def", "start", "(", "self", ")", ":", "super", "(", "Master", ",", "self", ")", ".", "start", "(", ")", "if", "check_user", "(", "self", ".", "config", "[", "'user'", "]", ")", ":", "self", ".", "action_log_info", "(", "'Starting up'", ")", "self", ...
Start the actual master. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`.
[ "Start", "the", "actual", "master", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L192-L206
train
saltstack/salt
salt/cli/daemons.py
Master.shutdown
def shutdown(self, exitcode=0, exitmsg=None): ''' If sub-classed, run any shutdown operations on this method. ''' self.shutdown_log_info() msg = 'The salt master is shutdown. ' if exitmsg is not None: exitmsg = msg + exitmsg else: exitmsg = msg.strip() super(Master, self).shutdown(exitcode, exitmsg)
python
def shutdown(self, exitcode=0, exitmsg=None): ''' If sub-classed, run any shutdown operations on this method. ''' self.shutdown_log_info() msg = 'The salt master is shutdown. ' if exitmsg is not None: exitmsg = msg + exitmsg else: exitmsg = msg.strip() super(Master, self).shutdown(exitcode, exitmsg)
[ "def", "shutdown", "(", "self", ",", "exitcode", "=", "0", ",", "exitmsg", "=", "None", ")", ":", "self", ".", "shutdown_log_info", "(", ")", "msg", "=", "'The salt master is shutdown. '", "if", "exitmsg", "is", "not", "None", ":", "exitmsg", "=", "msg", ...
If sub-classed, run any shutdown operations on this method.
[ "If", "sub", "-", "classed", "run", "any", "shutdown", "operations", "on", "this", "method", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L208-L218
train
saltstack/salt
salt/cli/daemons.py
Minion.prepare
def prepare(self): ''' Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Minion, self).prepare() try: if self.config['verify_env']: confd = self.config.get('default_include') if confd: # If 'default_include' is specified in config, then use it if '*' in confd: # Value is of the form "minion.d/*.conf" confd = os.path.dirname(confd) if not os.path.isabs(confd): # If configured 'default_include' is not an absolute # path, consider it relative to folder of 'conf_file' # (/etc/salt by default) confd = os.path.join( os.path.dirname(self.config['conf_file']), confd ) else: confd = os.path.join( os.path.dirname(self.config['conf_file']), 'minion.d' ) v_dirs = [ self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules'], confd, ] verify_env( v_dirs, self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) log.info('Setting up the Salt Minion "%s"', self.config['id']) migrations.migrate_paths(self.config) # Bail out if we find a process running and it matches out pidfile if self.check_running(): self.action_log_info('An instance is already running. Exiting') self.shutdown(1) transport = self.config.get('transport').lower() # TODO: AIO core is separate from transport if transport in ('zeromq', 'tcp', 'detect'): # Late import so logging works correctly import salt.minion # If the minion key has not been accepted, then Salt enters a loop # waiting for it, if we daemonize later then the minion could halt # the boot process waiting for a key to be accepted on the master. # This is the latest safe place to daemonize self.daemonize_if_required() self.set_pidfile() if self.config.get('master_type') == 'func': salt.minion.eval_master_func(self.config) self.minion = salt.minion.MinionManager(self.config) else: log.error( 'The transport \'%s\' is not supported. Please use one of ' 'the following: tcp, zeromq, or detect.', transport ) self.shutdown(1)
python
def prepare(self): ''' Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Minion, self).prepare() try: if self.config['verify_env']: confd = self.config.get('default_include') if confd: # If 'default_include' is specified in config, then use it if '*' in confd: # Value is of the form "minion.d/*.conf" confd = os.path.dirname(confd) if not os.path.isabs(confd): # If configured 'default_include' is not an absolute # path, consider it relative to folder of 'conf_file' # (/etc/salt by default) confd = os.path.join( os.path.dirname(self.config['conf_file']), confd ) else: confd = os.path.join( os.path.dirname(self.config['conf_file']), 'minion.d' ) v_dirs = [ self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules'], confd, ] verify_env( v_dirs, self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) log.info('Setting up the Salt Minion "%s"', self.config['id']) migrations.migrate_paths(self.config) # Bail out if we find a process running and it matches out pidfile if self.check_running(): self.action_log_info('An instance is already running. Exiting') self.shutdown(1) transport = self.config.get('transport').lower() # TODO: AIO core is separate from transport if transport in ('zeromq', 'tcp', 'detect'): # Late import so logging works correctly import salt.minion # If the minion key has not been accepted, then Salt enters a loop # waiting for it, if we daemonize later then the minion could halt # the boot process waiting for a key to be accepted on the master. # This is the latest safe place to daemonize self.daemonize_if_required() self.set_pidfile() if self.config.get('master_type') == 'func': salt.minion.eval_master_func(self.config) self.minion = salt.minion.MinionManager(self.config) else: log.error( 'The transport \'%s\' is not supported. Please use one of ' 'the following: tcp, zeromq, or detect.', transport ) self.shutdown(1)
[ "def", "prepare", "(", "self", ")", ":", "super", "(", "Minion", ",", "self", ")", ".", "prepare", "(", ")", "try", ":", "if", "self", ".", "config", "[", "'verify_env'", "]", ":", "confd", "=", "self", ".", "config", ".", "get", "(", "'default_inc...
Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare()
[ "Run", "the", "preparation", "sequence", "required", "to", "start", "a", "salt", "minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L233-L311
train
saltstack/salt
salt/cli/daemons.py
Minion.start
def start(self): ''' Start the actual minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Minion, self).start() while True: try: self._real_start() except SaltClientError as exc: # Restart for multi_master failover when daemonized if self.options.daemon: continue break
python
def start(self): ''' Start the actual minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Minion, self).start() while True: try: self._real_start() except SaltClientError as exc: # Restart for multi_master failover when daemonized if self.options.daemon: continue break
[ "def", "start", "(", "self", ")", ":", "super", "(", "Minion", ",", "self", ")", ".", "start", "(", ")", "while", "True", ":", "try", ":", "self", ".", "_real_start", "(", ")", "except", "SaltClientError", "as", "exc", ":", "# Restart for multi_master fa...
Start the actual minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`.
[ "Start", "the", "actual", "minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L313-L331
train
saltstack/salt
salt/cli/daemons.py
Minion.call
def call(self, cleanup_protecteds): ''' Start the actual minion as a caller minion. cleanup_protecteds is list of yard host addresses that should not be cleaned up this is to fix race condition when salt-caller minion starts up If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' try: self.prepare() if check_user(self.config['user']): self.minion.opts['__role'] = kinds.APPL_KIND_NAMES[kinds.applKinds.caller] self.minion.call_in() except (KeyboardInterrupt, SaltSystemExit) as exc: self.action_log_info('Stopping') if isinstance(exc, KeyboardInterrupt): log.warning('Exiting on Ctrl-c') self.shutdown() else: log.error(exc) self.shutdown(exc.code)
python
def call(self, cleanup_protecteds): ''' Start the actual minion as a caller minion. cleanup_protecteds is list of yard host addresses that should not be cleaned up this is to fix race condition when salt-caller minion starts up If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' try: self.prepare() if check_user(self.config['user']): self.minion.opts['__role'] = kinds.APPL_KIND_NAMES[kinds.applKinds.caller] self.minion.call_in() except (KeyboardInterrupt, SaltSystemExit) as exc: self.action_log_info('Stopping') if isinstance(exc, KeyboardInterrupt): log.warning('Exiting on Ctrl-c') self.shutdown() else: log.error(exc) self.shutdown(exc.code)
[ "def", "call", "(", "self", ",", "cleanup_protecteds", ")", ":", "try", ":", "self", ".", "prepare", "(", ")", "if", "check_user", "(", "self", ".", "config", "[", "'user'", "]", ")", ":", "self", ".", "minion", ".", "opts", "[", "'__role'", "]", "...
Start the actual minion as a caller minion. cleanup_protecteds is list of yard host addresses that should not be cleaned up this is to fix race condition when salt-caller minion starts up If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`.
[ "Start", "the", "actual", "minion", "as", "a", "caller", "minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L350-L375
train
saltstack/salt
salt/cli/daemons.py
Minion.shutdown
def shutdown(self, exitcode=0, exitmsg=None): ''' If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg ''' self.action_log_info('Shutting down') if hasattr(self, 'minion') and hasattr(self.minion, 'destroy'): self.minion.destroy() super(Minion, self).shutdown( exitcode, ('The Salt {0} is shutdown. {1}'.format( self.__class__.__name__, (exitmsg or '')).strip()))
python
def shutdown(self, exitcode=0, exitmsg=None): ''' If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg ''' self.action_log_info('Shutting down') if hasattr(self, 'minion') and hasattr(self.minion, 'destroy'): self.minion.destroy() super(Minion, self).shutdown( exitcode, ('The Salt {0} is shutdown. {1}'.format( self.__class__.__name__, (exitmsg or '')).strip()))
[ "def", "shutdown", "(", "self", ",", "exitcode", "=", "0", ",", "exitmsg", "=", "None", ")", ":", "self", ".", "action_log_info", "(", "'Shutting down'", ")", "if", "hasattr", "(", "self", ",", "'minion'", ")", "and", "hasattr", "(", "self", ".", "mini...
If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg
[ "If", "sub", "-", "classed", "run", "any", "shutdown", "operations", "on", "this", "method", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L377-L389
train
saltstack/salt
salt/cli/daemons.py
ProxyMinion.prepare
def prepare(self): ''' Run the preparation sequence required to start a salt proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(ProxyMinion, self).prepare() if not self.values.proxyid: self.error('salt-proxy requires --proxyid') # Proxies get their ID from the command line. This may need to change in # the future. # We used to set this here. Now it is set in ProxyMinionOptionParser # by passing it via setup_config to config.minion_config # self.config['id'] = self.values.proxyid try: if self.config['verify_env']: confd = self.config.get('default_include') if confd: # If 'default_include' is specified in config, then use it if '*' in confd: # Value is of the form "minion.d/*.conf" confd = os.path.dirname(confd) if not os.path.isabs(confd): # If configured 'default_include' is not an absolute # path, consider it relative to folder of 'conf_file' # (/etc/salt by default) confd = os.path.join( os.path.dirname(self.config['conf_file']), confd ) else: confd = os.path.join( os.path.dirname(self.config['conf_file']), 'proxy.d' ) v_dirs = [ self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules'], confd, ] verify_env( v_dirs, self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) self.action_log_info('Setting up "{0}"'.format(self.config['id'])) migrations.migrate_paths(self.config) # Bail out if we find a process running and it matches out pidfile if self.check_running(): self.action_log_info('An instance is already running. Exiting') self.shutdown(1) # TODO: AIO core is separate from transport # Late import so logging works correctly import salt.minion # If the minion key has not been accepted, then Salt enters a loop # waiting for it, if we daemonize later then the minion could halt # the boot process waiting for a key to be accepted on the master. # This is the latest safe place to daemonize self.daemonize_if_required() self.set_pidfile() if self.config.get('master_type') == 'func': salt.minion.eval_master_func(self.config) self.minion = salt.minion.ProxyMinionManager(self.config)
python
def prepare(self): ''' Run the preparation sequence required to start a salt proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(ProxyMinion, self).prepare() if not self.values.proxyid: self.error('salt-proxy requires --proxyid') # Proxies get their ID from the command line. This may need to change in # the future. # We used to set this here. Now it is set in ProxyMinionOptionParser # by passing it via setup_config to config.minion_config # self.config['id'] = self.values.proxyid try: if self.config['verify_env']: confd = self.config.get('default_include') if confd: # If 'default_include' is specified in config, then use it if '*' in confd: # Value is of the form "minion.d/*.conf" confd = os.path.dirname(confd) if not os.path.isabs(confd): # If configured 'default_include' is not an absolute # path, consider it relative to folder of 'conf_file' # (/etc/salt by default) confd = os.path.join( os.path.dirname(self.config['conf_file']), confd ) else: confd = os.path.join( os.path.dirname(self.config['conf_file']), 'proxy.d' ) v_dirs = [ self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules'], confd, ] verify_env( v_dirs, self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) self.action_log_info('Setting up "{0}"'.format(self.config['id'])) migrations.migrate_paths(self.config) # Bail out if we find a process running and it matches out pidfile if self.check_running(): self.action_log_info('An instance is already running. Exiting') self.shutdown(1) # TODO: AIO core is separate from transport # Late import so logging works correctly import salt.minion # If the minion key has not been accepted, then Salt enters a loop # waiting for it, if we daemonize later then the minion could halt # the boot process waiting for a key to be accepted on the master. # This is the latest safe place to daemonize self.daemonize_if_required() self.set_pidfile() if self.config.get('master_type') == 'func': salt.minion.eval_master_func(self.config) self.minion = salt.minion.ProxyMinionManager(self.config)
[ "def", "prepare", "(", "self", ")", ":", "super", "(", "ProxyMinion", ",", "self", ")", ".", "prepare", "(", ")", "if", "not", "self", ".", "values", ".", "proxyid", ":", "self", ".", "error", "(", "'salt-proxy requires --proxyid'", ")", "# Proxies get the...
Run the preparation sequence required to start a salt proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare()
[ "Run", "the", "preparation", "sequence", "required", "to", "start", "a", "salt", "proxy", "minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L404-L483
train
saltstack/salt
salt/cli/daemons.py
ProxyMinion.start
def start(self): ''' Start the actual proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(ProxyMinion, self).start() try: if check_user(self.config['user']): self.action_log_info('The Proxy Minion is starting up') self.verify_hash_type() self.minion.tune_in() if self.minion.restart: raise SaltClientError('Proxy Minion could not connect to Master') except (KeyboardInterrupt, SaltSystemExit) as exc: self.action_log_info('Proxy Minion Stopping') if isinstance(exc, KeyboardInterrupt): log.warning('Exiting on Ctrl-c') self.shutdown() else: log.error(exc) self.shutdown(exc.code)
python
def start(self): ''' Start the actual proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(ProxyMinion, self).start() try: if check_user(self.config['user']): self.action_log_info('The Proxy Minion is starting up') self.verify_hash_type() self.minion.tune_in() if self.minion.restart: raise SaltClientError('Proxy Minion could not connect to Master') except (KeyboardInterrupt, SaltSystemExit) as exc: self.action_log_info('Proxy Minion Stopping') if isinstance(exc, KeyboardInterrupt): log.warning('Exiting on Ctrl-c') self.shutdown() else: log.error(exc) self.shutdown(exc.code)
[ "def", "start", "(", "self", ")", ":", "super", "(", "ProxyMinion", ",", "self", ")", ".", "start", "(", ")", "try", ":", "if", "check_user", "(", "self", ".", "config", "[", "'user'", "]", ")", ":", "self", ".", "action_log_info", "(", "'The Proxy M...
Start the actual proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`.
[ "Start", "the", "actual", "proxy", "minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L485-L510
train
saltstack/salt
salt/cli/daemons.py
ProxyMinion.shutdown
def shutdown(self, exitcode=0, exitmsg=None): ''' If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg ''' if hasattr(self, 'minion') and 'proxymodule' in self.minion.opts: proxy_fn = self.minion.opts['proxymodule'].loaded_base_name + '.shutdown' self.minion.opts['proxymodule'][proxy_fn](self.minion.opts) self.action_log_info('Shutting down') super(ProxyMinion, self).shutdown( exitcode, ('The Salt {0} is shutdown. {1}'.format( self.__class__.__name__, (exitmsg or '')).strip()))
python
def shutdown(self, exitcode=0, exitmsg=None): ''' If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg ''' if hasattr(self, 'minion') and 'proxymodule' in self.minion.opts: proxy_fn = self.minion.opts['proxymodule'].loaded_base_name + '.shutdown' self.minion.opts['proxymodule'][proxy_fn](self.minion.opts) self.action_log_info('Shutting down') super(ProxyMinion, self).shutdown( exitcode, ('The Salt {0} is shutdown. {1}'.format( self.__class__.__name__, (exitmsg or '')).strip()))
[ "def", "shutdown", "(", "self", ",", "exitcode", "=", "0", ",", "exitmsg", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "'minion'", ")", "and", "'proxymodule'", "in", "self", ".", "minion", ".", "opts", ":", "proxy_fn", "=", "self", ".",...
If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg
[ "If", "sub", "-", "classed", "run", "any", "shutdown", "operations", "on", "this", "method", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L512-L525
train
saltstack/salt
salt/cli/daemons.py
Syndic.prepare
def prepare(self): ''' Run the preparation sequence required to start a salt syndic minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Syndic, self).prepare() try: if self.config['verify_env']: verify_env( [ self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules'], ], self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) self.action_log_info('Setting up "{0}"'.format(self.config['id'])) # Late import so logging works correctly import salt.minion self.daemonize_if_required() self.syndic = salt.minion.SyndicManager(self.config) self.set_pidfile()
python
def prepare(self): ''' Run the preparation sequence required to start a salt syndic minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Syndic, self).prepare() try: if self.config['verify_env']: verify_env( [ self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules'], ], self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) self.action_log_info('Setting up "{0}"'.format(self.config['id'])) # Late import so logging works correctly import salt.minion self.daemonize_if_required() self.syndic = salt.minion.SyndicManager(self.config) self.set_pidfile()
[ "def", "prepare", "(", "self", ")", ":", "super", "(", "Syndic", ",", "self", ")", ".", "prepare", "(", ")", "try", ":", "if", "self", ".", "config", "[", "'verify_env'", "]", ":", "verify_env", "(", "[", "self", ".", "config", "[", "'pki_dir'", "]...
Run the preparation sequence required to start a salt syndic minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare()
[ "Run", "the", "preparation", "sequence", "required", "to", "start", "a", "salt", "syndic", "minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L534-L568
train
saltstack/salt
salt/cli/daemons.py
Syndic.start
def start(self): ''' Start the actual syndic. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Syndic, self).start() if check_user(self.config['user']): self.action_log_info('Starting up') self.verify_hash_type() try: self.syndic.tune_in() except KeyboardInterrupt: self.action_log_info('Stopping') self.shutdown()
python
def start(self): ''' Start the actual syndic. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Syndic, self).start() if check_user(self.config['user']): self.action_log_info('Starting up') self.verify_hash_type() try: self.syndic.tune_in() except KeyboardInterrupt: self.action_log_info('Stopping') self.shutdown()
[ "def", "start", "(", "self", ")", ":", "super", "(", "Syndic", ",", "self", ")", ".", "start", "(", ")", "if", "check_user", "(", "self", ".", "config", "[", "'user'", "]", ")", ":", "self", ".", "action_log_info", "(", "'Starting up'", ")", "self", ...
Start the actual syndic. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`.
[ "Start", "the", "actual", "syndic", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L570-L588
train
saltstack/salt
salt/cli/daemons.py
Syndic.shutdown
def shutdown(self, exitcode=0, exitmsg=None): ''' If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg ''' self.action_log_info('Shutting down') super(Syndic, self).shutdown( exitcode, ('The Salt {0} is shutdown. {1}'.format( self.__class__.__name__, (exitmsg or '')).strip()))
python
def shutdown(self, exitcode=0, exitmsg=None): ''' If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg ''' self.action_log_info('Shutting down') super(Syndic, self).shutdown( exitcode, ('The Salt {0} is shutdown. {1}'.format( self.__class__.__name__, (exitmsg or '')).strip()))
[ "def", "shutdown", "(", "self", ",", "exitcode", "=", "0", ",", "exitmsg", "=", "None", ")", ":", "self", ".", "action_log_info", "(", "'Shutting down'", ")", "super", "(", "Syndic", ",", "self", ")", ".", "shutdown", "(", "exitcode", ",", "(", "'The S...
If sub-classed, run any shutdown operations on this method. :param exitcode :param exitmsg
[ "If", "sub", "-", "classed", "run", "any", "shutdown", "operations", "on", "this", "method", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L590-L600
train
saltstack/salt
salt/modules/drac.py
__execute_cmd
def __execute_cmd(command): ''' Execute rac commands ''' cmd = __salt__['cmd.run_all']('racadm {0}'.format(command)) if cmd['retcode'] != 0: log.warning('racadm return an exit code \'%s\'.', cmd['retcode']) return False return True
python
def __execute_cmd(command): ''' Execute rac commands ''' cmd = __salt__['cmd.run_all']('racadm {0}'.format(command)) if cmd['retcode'] != 0: log.warning('racadm return an exit code \'%s\'.', cmd['retcode']) return False return True
[ "def", "__execute_cmd", "(", "command", ")", ":", "cmd", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'racadm {0}'", ".", "format", "(", "command", ")", ")", "if", "cmd", "[", "'retcode'", "]", "!=", "0", ":", "log", ".", "warning", "(", "'racadm ...
Execute rac commands
[ "Execute", "rac", "commands" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L48-L58
train
saltstack/salt
salt/modules/drac.py
nameservers
def nameservers(*ns): ''' Configure the nameservers on the DRAC CLI Example: .. code-block:: bash salt dell drac.nameservers [NAMESERVERS] salt dell drac.nameservers ns1.example.com ns2.example.com ''' if len(ns) > 2: log.warning('racadm only supports two nameservers') return False for i in range(1, len(ns) + 1): if not __execute_cmd('config -g cfgLanNetworking -o \ cfgDNSServer{0} {1}'.format(i, ns[i - 1])): return False return True
python
def nameservers(*ns): ''' Configure the nameservers on the DRAC CLI Example: .. code-block:: bash salt dell drac.nameservers [NAMESERVERS] salt dell drac.nameservers ns1.example.com ns2.example.com ''' if len(ns) > 2: log.warning('racadm only supports two nameservers') return False for i in range(1, len(ns) + 1): if not __execute_cmd('config -g cfgLanNetworking -o \ cfgDNSServer{0} {1}'.format(i, ns[i - 1])): return False return True
[ "def", "nameservers", "(", "*", "ns", ")", ":", "if", "len", "(", "ns", ")", ">", "2", ":", "log", ".", "warning", "(", "'racadm only supports two nameservers'", ")", "return", "False", "for", "i", "in", "range", "(", "1", ",", "len", "(", "ns", ")",...
Configure the nameservers on the DRAC CLI Example: .. code-block:: bash salt dell drac.nameservers [NAMESERVERS] salt dell drac.nameservers ns1.example.com ns2.example.com
[ "Configure", "the", "nameservers", "on", "the", "DRAC" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L98-L118
train
saltstack/salt
salt/modules/drac.py
syslog
def syslog(server, enable=True): ''' Configure syslog remote logging, by default syslog will automatically be enabled if a server is specified. However, if you want to disable syslog you will need to specify a server followed by False CLI Example: .. code-block:: bash salt dell drac.syslog [SYSLOG IP] [ENABLE/DISABLE] salt dell drac.syslog 0.0.0.0 False ''' if enable and __execute_cmd('config -g cfgRemoteHosts -o \ cfgRhostsSyslogEnable 1'): return __execute_cmd('config -g cfgRemoteHosts -o \ cfgRhostsSyslogServer1 {0}'.format(server)) return __execute_cmd('config -g cfgRemoteHosts -o cfgRhostsSyslogEnable 0')
python
def syslog(server, enable=True): ''' Configure syslog remote logging, by default syslog will automatically be enabled if a server is specified. However, if you want to disable syslog you will need to specify a server followed by False CLI Example: .. code-block:: bash salt dell drac.syslog [SYSLOG IP] [ENABLE/DISABLE] salt dell drac.syslog 0.0.0.0 False ''' if enable and __execute_cmd('config -g cfgRemoteHosts -o \ cfgRhostsSyslogEnable 1'): return __execute_cmd('config -g cfgRemoteHosts -o \ cfgRhostsSyslogServer1 {0}'.format(server)) return __execute_cmd('config -g cfgRemoteHosts -o cfgRhostsSyslogEnable 0')
[ "def", "syslog", "(", "server", ",", "enable", "=", "True", ")", ":", "if", "enable", "and", "__execute_cmd", "(", "'config -g cfgRemoteHosts -o \\\n cfgRhostsSyslogEnable 1'", ")", ":", "return", "__execute_cmd", "(", "'config -g cfgRemoteHosts -o \\\n ...
Configure syslog remote logging, by default syslog will automatically be enabled if a server is specified. However, if you want to disable syslog you will need to specify a server followed by False CLI Example: .. code-block:: bash salt dell drac.syslog [SYSLOG IP] [ENABLE/DISABLE] salt dell drac.syslog 0.0.0.0 False
[ "Configure", "syslog", "remote", "logging", "by", "default", "syslog", "will", "automatically", "be", "enabled", "if", "a", "server", "is", "specified", ".", "However", "if", "you", "want", "to", "disable", "syslog", "you", "will", "need", "to", "specify", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L121-L139
train
saltstack/salt
salt/modules/drac.py
list_users
def list_users(): ''' List all DRAC users CLI Example: .. code-block:: bash salt dell drac.list_users ''' users = {} _username = '' for idx in range(1, 17): cmd = __salt__['cmd.run_all']('racadm getconfig -g \ cfgUserAdmin -i {0}'.format(idx)) if cmd['retcode'] != 0: log.warning('racadm return an exit code \'%s\'.', cmd['retcode']) for user in cmd['stdout'].splitlines(): if not user.startswith('cfg'): continue (key, val) = user.split('=') if key.startswith('cfgUserAdminUserName'): _username = val.strip() if val: users[_username] = {'index': idx} else: break else: users[_username].update({key: val}) return users
python
def list_users(): ''' List all DRAC users CLI Example: .. code-block:: bash salt dell drac.list_users ''' users = {} _username = '' for idx in range(1, 17): cmd = __salt__['cmd.run_all']('racadm getconfig -g \ cfgUserAdmin -i {0}'.format(idx)) if cmd['retcode'] != 0: log.warning('racadm return an exit code \'%s\'.', cmd['retcode']) for user in cmd['stdout'].splitlines(): if not user.startswith('cfg'): continue (key, val) = user.split('=') if key.startswith('cfgUserAdminUserName'): _username = val.strip() if val: users[_username] = {'index': idx} else: break else: users[_username].update({key: val}) return users
[ "def", "list_users", "(", ")", ":", "users", "=", "{", "}", "_username", "=", "''", "for", "idx", "in", "range", "(", "1", ",", "17", ")", ":", "cmd", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'racadm getconfig -g \\\n cfgUserAdmin -i ...
List all DRAC users CLI Example: .. code-block:: bash salt dell drac.list_users
[ "List", "all", "DRAC", "users" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L162-L198
train
saltstack/salt
salt/modules/drac.py
delete_user
def delete_user(username, uid=None): ''' Delete a user CLI Example: .. code-block:: bash salt dell drac.delete_user [USERNAME] [UID - optional] salt dell drac.delete_user diana 4 ''' if uid is None: user = list_users() uid = user[username]['index'] if uid: return __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminUserName -i {0} ""'.format(uid)) else: log.warning('\'%s\' does not exist', username) return False return True
python
def delete_user(username, uid=None): ''' Delete a user CLI Example: .. code-block:: bash salt dell drac.delete_user [USERNAME] [UID - optional] salt dell drac.delete_user diana 4 ''' if uid is None: user = list_users() uid = user[username]['index'] if uid: return __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminUserName -i {0} ""'.format(uid)) else: log.warning('\'%s\' does not exist', username) return False return True
[ "def", "delete_user", "(", "username", ",", "uid", "=", "None", ")", ":", "if", "uid", "is", "None", ":", "user", "=", "list_users", "(", ")", "uid", "=", "user", "[", "username", "]", "[", "'index'", "]", "if", "uid", ":", "return", "__execute_cmd",...
Delete a user CLI Example: .. code-block:: bash salt dell drac.delete_user [USERNAME] [UID - optional] salt dell drac.delete_user diana 4
[ "Delete", "a", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L201-L224
train
saltstack/salt
salt/modules/drac.py
change_password
def change_password(username, password, uid=None): ''' Change users password CLI Example: .. code-block:: bash salt dell drac.change_password [USERNAME] [PASSWORD] [UID - optional] salt dell drac.change_password diana secret ''' if uid is None: user = list_users() uid = user[username]['index'] if uid: return __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminPassword -i {0} {1}'.format(uid, password)) else: log.warning('\'%s\' does not exist', username) return False return True
python
def change_password(username, password, uid=None): ''' Change users password CLI Example: .. code-block:: bash salt dell drac.change_password [USERNAME] [PASSWORD] [UID - optional] salt dell drac.change_password diana secret ''' if uid is None: user = list_users() uid = user[username]['index'] if uid: return __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminPassword -i {0} {1}'.format(uid, password)) else: log.warning('\'%s\' does not exist', username) return False return True
[ "def", "change_password", "(", "username", ",", "password", ",", "uid", "=", "None", ")", ":", "if", "uid", "is", "None", ":", "user", "=", "list_users", "(", ")", "uid", "=", "user", "[", "username", "]", "[", "'index'", "]", "if", "uid", ":", "re...
Change users password CLI Example: .. code-block:: bash salt dell drac.change_password [USERNAME] [PASSWORD] [UID - optional] salt dell drac.change_password diana secret
[ "Change", "users", "password" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L227-L249
train
saltstack/salt
salt/modules/drac.py
create_user
def create_user(username, password, permissions, users=None): ''' Create user accounts CLI Example: .. code-block:: bash salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES] salt dell drac.create_user diana secret login,test_alerts,clear_logs DRAC Privileges * login : Login to iDRAC * drac : Configure iDRAC * user_management : Configure Users * clear_logs : Clear Logs * server_control_commands : Execute Server Control Commands * console_redirection : Access Console Redirection * virtual_media : Access Virtual Media * test_alerts : Test Alerts * debug_commands : Execute Debug Commands ''' _uids = set() if users is None: users = list_users() if username in users: log.warning('\'%s\' already exists', username) return False for idx in six.iterkeys(users): _uids.add(users[idx]['index']) uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop() # Create user accountvfirst if not __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminUserName -i {0} {1}'.format(uid, username)): delete_user(username, uid) return False # Configure users permissions if not set_permissions(username, permissions, uid): log.warning('unable to set user permissions') delete_user(username, uid) return False # Configure users password if not change_password(username, password, uid): log.warning('unable to set user password') delete_user(username, uid) return False # Enable users admin if not __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminEnable -i {0} 1'.format(uid)): delete_user(username, uid) return False return True
python
def create_user(username, password, permissions, users=None): ''' Create user accounts CLI Example: .. code-block:: bash salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES] salt dell drac.create_user diana secret login,test_alerts,clear_logs DRAC Privileges * login : Login to iDRAC * drac : Configure iDRAC * user_management : Configure Users * clear_logs : Clear Logs * server_control_commands : Execute Server Control Commands * console_redirection : Access Console Redirection * virtual_media : Access Virtual Media * test_alerts : Test Alerts * debug_commands : Execute Debug Commands ''' _uids = set() if users is None: users = list_users() if username in users: log.warning('\'%s\' already exists', username) return False for idx in six.iterkeys(users): _uids.add(users[idx]['index']) uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop() # Create user accountvfirst if not __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminUserName -i {0} {1}'.format(uid, username)): delete_user(username, uid) return False # Configure users permissions if not set_permissions(username, permissions, uid): log.warning('unable to set user permissions') delete_user(username, uid) return False # Configure users password if not change_password(username, password, uid): log.warning('unable to set user password') delete_user(username, uid) return False # Enable users admin if not __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminEnable -i {0} 1'.format(uid)): delete_user(username, uid) return False return True
[ "def", "create_user", "(", "username", ",", "password", ",", "permissions", ",", "users", "=", "None", ")", ":", "_uids", "=", "set", "(", ")", "if", "users", "is", "None", ":", "users", "=", "list_users", "(", ")", "if", "username", "in", "users", "...
Create user accounts CLI Example: .. code-block:: bash salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES] salt dell drac.create_user diana secret login,test_alerts,clear_logs DRAC Privileges * login : Login to iDRAC * drac : Configure iDRAC * user_management : Configure Users * clear_logs : Clear Logs * server_control_commands : Execute Server Control Commands * console_redirection : Access Console Redirection * virtual_media : Access Virtual Media * test_alerts : Test Alerts * debug_commands : Execute Debug Commands
[ "Create", "user", "accounts" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L252-L312
train
saltstack/salt
salt/modules/drac.py
set_permissions
def set_permissions(username, permissions, uid=None): ''' Configure users permissions CLI Example: .. code-block:: bash salt dell drac.set_permissions [USERNAME] [PRIVILEGES] [USER INDEX - optional] salt dell drac.set_permissions diana login,test_alerts,clear_logs 4 DRAC Privileges * login : Login to iDRAC * drac : Configure iDRAC * user_management : Configure Users * clear_logs : Clear Logs * server_control_commands : Execute Server Control Commands * console_redirection : Access Console Redirection * virtual_media : Access Virtual Media * test_alerts : Test Alerts * debug_commands : Execute Debug Commands ''' privileges = {'login': '0x0000001', 'drac': '0x0000002', 'user_management': '0x0000004', 'clear_logs': '0x0000008', 'server_control_commands': '0x0000010', 'console_redirection': '0x0000020', 'virtual_media': '0x0000040', 'test_alerts': '0x0000080', 'debug_commands': '0x0000100'} permission = 0 # When users don't provide a user ID we need to search for this if uid is None: user = list_users() uid = user[username]['index'] # Generate privilege bit mask for i in permissions.split(','): perm = i.strip() if perm in privileges: permission += int(privileges[perm], 16) return __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminPrivilege -i {0} 0x{1:08X}'.format(uid, permission))
python
def set_permissions(username, permissions, uid=None): ''' Configure users permissions CLI Example: .. code-block:: bash salt dell drac.set_permissions [USERNAME] [PRIVILEGES] [USER INDEX - optional] salt dell drac.set_permissions diana login,test_alerts,clear_logs 4 DRAC Privileges * login : Login to iDRAC * drac : Configure iDRAC * user_management : Configure Users * clear_logs : Clear Logs * server_control_commands : Execute Server Control Commands * console_redirection : Access Console Redirection * virtual_media : Access Virtual Media * test_alerts : Test Alerts * debug_commands : Execute Debug Commands ''' privileges = {'login': '0x0000001', 'drac': '0x0000002', 'user_management': '0x0000004', 'clear_logs': '0x0000008', 'server_control_commands': '0x0000010', 'console_redirection': '0x0000020', 'virtual_media': '0x0000040', 'test_alerts': '0x0000080', 'debug_commands': '0x0000100'} permission = 0 # When users don't provide a user ID we need to search for this if uid is None: user = list_users() uid = user[username]['index'] # Generate privilege bit mask for i in permissions.split(','): perm = i.strip() if perm in privileges: permission += int(privileges[perm], 16) return __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminPrivilege -i {0} 0x{1:08X}'.format(uid, permission))
[ "def", "set_permissions", "(", "username", ",", "permissions", ",", "uid", "=", "None", ")", ":", "privileges", "=", "{", "'login'", ":", "'0x0000001'", ",", "'drac'", ":", "'0x0000002'", ",", "'user_management'", ":", "'0x0000004'", ",", "'clear_logs'", ":", ...
Configure users permissions CLI Example: .. code-block:: bash salt dell drac.set_permissions [USERNAME] [PRIVILEGES] [USER INDEX - optional] salt dell drac.set_permissions diana login,test_alerts,clear_logs 4 DRAC Privileges * login : Login to iDRAC * drac : Configure iDRAC * user_management : Configure Users * clear_logs : Clear Logs * server_control_commands : Execute Server Control Commands * console_redirection : Access Console Redirection * virtual_media : Access Virtual Media * test_alerts : Test Alerts * debug_commands : Execute Debug Commands
[ "Configure", "users", "permissions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L315-L362
train
saltstack/salt
salt/modules/drac.py
server_pxe
def server_pxe(): ''' Configure server to PXE perform a one off PXE boot CLI Example: .. code-block:: bash salt dell drac.server_pxe ''' if __execute_cmd('config -g cfgServerInfo -o \ cfgServerFirstBootDevice PXE'): if __execute_cmd('config -g cfgServerInfo -o cfgServerBootOnce 1'): return server_reboot else: log.warning('failed to set boot order') return False log.warning('failed to configure PXE boot') return False
python
def server_pxe(): ''' Configure server to PXE perform a one off PXE boot CLI Example: .. code-block:: bash salt dell drac.server_pxe ''' if __execute_cmd('config -g cfgServerInfo -o \ cfgServerFirstBootDevice PXE'): if __execute_cmd('config -g cfgServerInfo -o cfgServerBootOnce 1'): return server_reboot else: log.warning('failed to set boot order') return False log.warning('failed to configure PXE boot') return False
[ "def", "server_pxe", "(", ")", ":", "if", "__execute_cmd", "(", "'config -g cfgServerInfo -o \\\n cfgServerFirstBootDevice PXE'", ")", ":", "if", "__execute_cmd", "(", "'config -g cfgServerInfo -o cfgServerBootOnce 1'", ")", ":", "return", "server_reboot", "else", ...
Configure server to PXE perform a one off PXE boot CLI Example: .. code-block:: bash salt dell drac.server_pxe
[ "Configure", "server", "to", "PXE", "perform", "a", "one", "off", "PXE", "boot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L450-L469
train
saltstack/salt
scripts/suse/yum/plugins/yumnotify.py
_get_mtime
def _get_mtime(): """ Get the modified time of the RPM Database. Returns: Unix ticks """ return os.path.exists(RPM_PATH) and int(os.path.getmtime(RPM_PATH)) or 0
python
def _get_mtime(): """ Get the modified time of the RPM Database. Returns: Unix ticks """ return os.path.exists(RPM_PATH) and int(os.path.getmtime(RPM_PATH)) or 0
[ "def", "_get_mtime", "(", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "RPM_PATH", ")", "and", "int", "(", "os", ".", "path", ".", "getmtime", "(", "RPM_PATH", ")", ")", "or", "0" ]
Get the modified time of the RPM Database. Returns: Unix ticks
[ "Get", "the", "modified", "time", "of", "the", "RPM", "Database", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/scripts/suse/yum/plugins/yumnotify.py#L18-L25
train
saltstack/salt
scripts/suse/yum/plugins/yumnotify.py
_get_checksum
def _get_checksum(): """ Get the checksum of the RPM Database. Returns: hexdigest """ digest = hashlib.sha256() with open(RPM_PATH, "rb") as rpm_db_fh: while True: buff = rpm_db_fh.read(0x1000) if not buff: break digest.update(buff) return digest.hexdigest()
python
def _get_checksum(): """ Get the checksum of the RPM Database. Returns: hexdigest """ digest = hashlib.sha256() with open(RPM_PATH, "rb") as rpm_db_fh: while True: buff = rpm_db_fh.read(0x1000) if not buff: break digest.update(buff) return digest.hexdigest()
[ "def", "_get_checksum", "(", ")", ":", "digest", "=", "hashlib", ".", "sha256", "(", ")", "with", "open", "(", "RPM_PATH", ",", "\"rb\"", ")", "as", "rpm_db_fh", ":", "while", "True", ":", "buff", "=", "rpm_db_fh", ".", "read", "(", "0x1000", ")", "i...
Get the checksum of the RPM Database. Returns: hexdigest
[ "Get", "the", "checksum", "of", "the", "RPM", "Database", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/scripts/suse/yum/plugins/yumnotify.py#L28-L42
train
saltstack/salt
scripts/suse/yum/plugins/yumnotify.py
posttrans_hook
def posttrans_hook(conduit): """ Hook after the package installation transaction. :param conduit: :return: """ # Integrate Yum with Salt if 'SALT_RUNNING' not in os.environ: with open(CK_PATH, 'w') as ck_fh: ck_fh.write('{chksum} {mtime}\n'.format(chksum=_get_checksum(), mtime=_get_mtime()))
python
def posttrans_hook(conduit): """ Hook after the package installation transaction. :param conduit: :return: """ # Integrate Yum with Salt if 'SALT_RUNNING' not in os.environ: with open(CK_PATH, 'w') as ck_fh: ck_fh.write('{chksum} {mtime}\n'.format(chksum=_get_checksum(), mtime=_get_mtime()))
[ "def", "posttrans_hook", "(", "conduit", ")", ":", "# Integrate Yum with Salt", "if", "'SALT_RUNNING'", "not", "in", "os", ".", "environ", ":", "with", "open", "(", "CK_PATH", ",", "'w'", ")", "as", "ck_fh", ":", "ck_fh", ".", "write", "(", "'{chksum} {mtime...
Hook after the package installation transaction. :param conduit: :return:
[ "Hook", "after", "the", "package", "installation", "transaction", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/scripts/suse/yum/plugins/yumnotify.py#L45-L55
train
saltstack/salt
salt/modules/postfix.py
_parse_master
def _parse_master(path=MASTER_CF): ''' Parse the master.cf file. This file is essentially a whitespace-delimited columnar file. The columns are: service, type, private (yes), unpriv (yes), chroot (yes), wakeup (never), maxproc (100), command + args. This function parses out the columns, leaving empty lines and comments intact. Where the value doesn't detract from the default, a dash (-) will be used. Returns a dict of the active config lines, and a list of the entire file, in order. These compliment each other. ''' with salt.utils.files.fopen(path, 'r') as fh_: full_conf = salt.utils.stringutils.to_unicode(fh_.read()) # Condense the file based on line continuations, but keep order, comments # and whitespace conf_list = [] conf_dict = {} for line in full_conf.splitlines(): if not line.strip() or line.strip().startswith('#'): conf_list.append(line) continue comps = line.strip().split() conf_line = { 'service': comps[0], 'conn_type': comps[1], 'private': comps[2], 'unpriv': comps[3], 'chroot': comps[4], 'wakeup': comps[5], 'maxproc': comps[6], 'command': ' '.join(comps[7:]), } dict_key = '{0} {1}'.format(comps[0], comps[1]) conf_list.append(conf_line) conf_dict[dict_key] = conf_line return conf_dict, conf_list
python
def _parse_master(path=MASTER_CF): ''' Parse the master.cf file. This file is essentially a whitespace-delimited columnar file. The columns are: service, type, private (yes), unpriv (yes), chroot (yes), wakeup (never), maxproc (100), command + args. This function parses out the columns, leaving empty lines and comments intact. Where the value doesn't detract from the default, a dash (-) will be used. Returns a dict of the active config lines, and a list of the entire file, in order. These compliment each other. ''' with salt.utils.files.fopen(path, 'r') as fh_: full_conf = salt.utils.stringutils.to_unicode(fh_.read()) # Condense the file based on line continuations, but keep order, comments # and whitespace conf_list = [] conf_dict = {} for line in full_conf.splitlines(): if not line.strip() or line.strip().startswith('#'): conf_list.append(line) continue comps = line.strip().split() conf_line = { 'service': comps[0], 'conn_type': comps[1], 'private': comps[2], 'unpriv': comps[3], 'chroot': comps[4], 'wakeup': comps[5], 'maxproc': comps[6], 'command': ' '.join(comps[7:]), } dict_key = '{0} {1}'.format(comps[0], comps[1]) conf_list.append(conf_line) conf_dict[dict_key] = conf_line return conf_dict, conf_list
[ "def", "_parse_master", "(", "path", "=", "MASTER_CF", ")", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ")", "as", "fh_", ":", "full_conf", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", ...
Parse the master.cf file. This file is essentially a whitespace-delimited columnar file. The columns are: service, type, private (yes), unpriv (yes), chroot (yes), wakeup (never), maxproc (100), command + args. This function parses out the columns, leaving empty lines and comments intact. Where the value doesn't detract from the default, a dash (-) will be used. Returns a dict of the active config lines, and a list of the entire file, in order. These compliment each other.
[ "Parse", "the", "master", ".", "cf", "file", ".", "This", "file", "is", "essentially", "a", "whitespace", "-", "delimited", "columnar", "file", ".", "The", "columns", "are", ":", "service", "type", "private", "(", "yes", ")", "unpriv", "(", "yes", ")", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L45-L84
train
saltstack/salt
salt/modules/postfix.py
set_master
def set_master(service, conn_type, private='y', unpriv='y', chroot='y', wakeup='n', maxproc='100', command='', write_conf=True, path=MASTER_CF): ''' Set a single config value in the master.cf file. If the value does not already exist, it will be appended to the end. Because of shell parsing issues, '-' cannot be set as a value, as is normal in the master.cf file; either 'y', 'n' or a number should be used when calling this function from the command line. If the value used matches the default, it will internally be converted to a '-'. Calling this function from the Python API is not affected by this limitation The settings and their default values, in order, are: service (required), conn_type (required), private (y), unpriv (y), chroot (y), wakeup (n), maxproc (100), command (required). By default, this function will write out the changes to the master.cf file, and then returns the full contents of the file. By setting the ``write_conf`` option to ``False``, it will skip writing the file. CLI Example: salt <minion> postfix.set_master smtp inet n y n n 100 smtpd ''' conf_dict, conf_list = _parse_master(path) new_conf = [] dict_key = '{0} {1}'.format(service, conn_type) new_line = _format_master( service, conn_type, private, unpriv, chroot, wakeup, maxproc, command, ) for line in conf_list: if isinstance(line, dict): if line['service'] == service and line['conn_type'] == conn_type: # This is the one line that we're changing new_conf.append(new_line) else: # No changes to this line, but it still needs to be # formatted properly new_conf.append(_format_master(**line)) else: # This line is a comment or is empty new_conf.append(line) if dict_key not in conf_dict: # This config value does not exist, so append it to the end new_conf.append(new_line) if write_conf: _write_conf(new_conf, path) return '\n'.join(new_conf)
python
def set_master(service, conn_type, private='y', unpriv='y', chroot='y', wakeup='n', maxproc='100', command='', write_conf=True, path=MASTER_CF): ''' Set a single config value in the master.cf file. If the value does not already exist, it will be appended to the end. Because of shell parsing issues, '-' cannot be set as a value, as is normal in the master.cf file; either 'y', 'n' or a number should be used when calling this function from the command line. If the value used matches the default, it will internally be converted to a '-'. Calling this function from the Python API is not affected by this limitation The settings and their default values, in order, are: service (required), conn_type (required), private (y), unpriv (y), chroot (y), wakeup (n), maxproc (100), command (required). By default, this function will write out the changes to the master.cf file, and then returns the full contents of the file. By setting the ``write_conf`` option to ``False``, it will skip writing the file. CLI Example: salt <minion> postfix.set_master smtp inet n y n n 100 smtpd ''' conf_dict, conf_list = _parse_master(path) new_conf = [] dict_key = '{0} {1}'.format(service, conn_type) new_line = _format_master( service, conn_type, private, unpriv, chroot, wakeup, maxproc, command, ) for line in conf_list: if isinstance(line, dict): if line['service'] == service and line['conn_type'] == conn_type: # This is the one line that we're changing new_conf.append(new_line) else: # No changes to this line, but it still needs to be # formatted properly new_conf.append(_format_master(**line)) else: # This line is a comment or is empty new_conf.append(line) if dict_key not in conf_dict: # This config value does not exist, so append it to the end new_conf.append(new_line) if write_conf: _write_conf(new_conf, path) return '\n'.join(new_conf)
[ "def", "set_master", "(", "service", ",", "conn_type", ",", "private", "=", "'y'", ",", "unpriv", "=", "'y'", ",", "chroot", "=", "'y'", ",", "wakeup", "=", "'n'", ",", "maxproc", "=", "'100'", ",", "command", "=", "''", ",", "write_conf", "=", "True...
Set a single config value in the master.cf file. If the value does not already exist, it will be appended to the end. Because of shell parsing issues, '-' cannot be set as a value, as is normal in the master.cf file; either 'y', 'n' or a number should be used when calling this function from the command line. If the value used matches the default, it will internally be converted to a '-'. Calling this function from the Python API is not affected by this limitation The settings and their default values, in order, are: service (required), conn_type (required), private (y), unpriv (y), chroot (y), wakeup (n), maxproc (100), command (required). By default, this function will write out the changes to the master.cf file, and then returns the full contents of the file. By setting the ``write_conf`` option to ``False``, it will skip writing the file. CLI Example: salt <minion> postfix.set_master smtp inet n y n n 100 smtpd
[ "Set", "a", "single", "config", "value", "in", "the", "master", ".", "cf", "file", ".", "If", "the", "value", "does", "not", "already", "exist", "it", "will", "be", "appended", "to", "the", "end", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L104-L169
train
saltstack/salt
salt/modules/postfix.py
_format_master
def _format_master(service, conn_type, private, unpriv, chroot, wakeup, maxproc, command): ''' Format the given values into the style of line normally used in the master.cf file. ''' #========================================================================== #service type private unpriv chroot wakeup maxproc command + args # (yes) (yes) (yes) (never) (100) #========================================================================== #smtp inet n - n - - smtpd if private == 'y': private = '-' if unpriv == 'y': unpriv = '-' if chroot == 'y': chroot = '-' if wakeup == 'n': wakeup = '-' maxproc = six.text_type(maxproc) if maxproc == '100': maxproc = '-' conf_line = '{0:9s} {1:5s} {2:7s} {3:7s} {4:7s} {5:7s} {6:7s} {7}'.format( service, conn_type, private, unpriv, chroot, wakeup, maxproc, command, ) #print(conf_line) return conf_line
python
def _format_master(service, conn_type, private, unpriv, chroot, wakeup, maxproc, command): ''' Format the given values into the style of line normally used in the master.cf file. ''' #========================================================================== #service type private unpriv chroot wakeup maxproc command + args # (yes) (yes) (yes) (never) (100) #========================================================================== #smtp inet n - n - - smtpd if private == 'y': private = '-' if unpriv == 'y': unpriv = '-' if chroot == 'y': chroot = '-' if wakeup == 'n': wakeup = '-' maxproc = six.text_type(maxproc) if maxproc == '100': maxproc = '-' conf_line = '{0:9s} {1:5s} {2:7s} {3:7s} {4:7s} {5:7s} {6:7s} {7}'.format( service, conn_type, private, unpriv, chroot, wakeup, maxproc, command, ) #print(conf_line) return conf_line
[ "def", "_format_master", "(", "service", ",", "conn_type", ",", "private", ",", "unpriv", ",", "chroot", ",", "wakeup", ",", "maxproc", ",", "command", ")", ":", "#==========================================================================", "#service type private unpriv c...
Format the given values into the style of line normally used in the master.cf file.
[ "Format", "the", "given", "values", "into", "the", "style", "of", "line", "normally", "used", "in", "the", "master", ".", "cf", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L172-L216
train
saltstack/salt
salt/modules/postfix.py
_parse_main
def _parse_main(path=MAIN_CF): ''' Parse files in the style of main.cf. This is not just a "name = value" file; there are other rules: * Comments start with # * Any whitespace at the beginning of a line denotes that that line is a continuation from the previous line. * The whitespace rule applies to comments. * Keys defined in the file may be referred to as variables further down in the file. ''' with salt.utils.files.fopen(path, 'r') as fh_: full_conf = salt.utils.stringutils.to_unicode(fh_.read()) # Condense the file based on line continuations, but keep order, comments # and whitespace conf_list = [] for line in full_conf.splitlines(): if not line.strip(): conf_list.append(line) continue if re.match(SWWS, line): if not conf_list: # This should only happen at the top of the file conf_list.append(line) continue if not isinstance(conf_list[-1], six.string_types): conf_list[-1] = '' # This line is a continuation of the previous line conf_list[-1] = '\n'.join([conf_list[-1], line]) else: conf_list.append(line) # Extract just the actual key/value pairs pairs = {} for line in conf_list: if not line.strip(): continue if line.startswith('#'): continue comps = line.split('=') pairs[comps[0].strip()] = '='.join(comps[1:]).strip() # Return both sets of data, they compliment each other elsewhere return pairs, conf_list
python
def _parse_main(path=MAIN_CF): ''' Parse files in the style of main.cf. This is not just a "name = value" file; there are other rules: * Comments start with # * Any whitespace at the beginning of a line denotes that that line is a continuation from the previous line. * The whitespace rule applies to comments. * Keys defined in the file may be referred to as variables further down in the file. ''' with salt.utils.files.fopen(path, 'r') as fh_: full_conf = salt.utils.stringutils.to_unicode(fh_.read()) # Condense the file based on line continuations, but keep order, comments # and whitespace conf_list = [] for line in full_conf.splitlines(): if not line.strip(): conf_list.append(line) continue if re.match(SWWS, line): if not conf_list: # This should only happen at the top of the file conf_list.append(line) continue if not isinstance(conf_list[-1], six.string_types): conf_list[-1] = '' # This line is a continuation of the previous line conf_list[-1] = '\n'.join([conf_list[-1], line]) else: conf_list.append(line) # Extract just the actual key/value pairs pairs = {} for line in conf_list: if not line.strip(): continue if line.startswith('#'): continue comps = line.split('=') pairs[comps[0].strip()] = '='.join(comps[1:]).strip() # Return both sets of data, they compliment each other elsewhere return pairs, conf_list
[ "def", "_parse_main", "(", "path", "=", "MAIN_CF", ")", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ")", "as", "fh_", ":", "full_conf", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(",...
Parse files in the style of main.cf. This is not just a "name = value" file; there are other rules: * Comments start with # * Any whitespace at the beginning of a line denotes that that line is a continuation from the previous line. * The whitespace rule applies to comments. * Keys defined in the file may be referred to as variables further down in the file.
[ "Parse", "files", "in", "the", "style", "of", "main", ".", "cf", ".", "This", "is", "not", "just", "a", "name", "=", "value", "file", ";", "there", "are", "other", "rules", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L219-L264
train
saltstack/salt
salt/modules/postfix.py
set_main
def set_main(key, value, path=MAIN_CF): ''' Set a single config value in the main.cf file. If the value does not already exist, it will be appended to the end. CLI Example: salt <minion> postfix.set_main mailq_path /usr/bin/mailq ''' pairs, conf_list = _parse_main(path) new_conf = [] key_line_match = re.compile("^{0}([\\s=]|$)".format(re.escape(key))) if key in pairs: for line in conf_list: if re.match(key_line_match, line): new_conf.append('{0} = {1}'.format(key, value)) else: new_conf.append(line) else: conf_list.append('{0} = {1}'.format(key, value)) new_conf = conf_list _write_conf(new_conf, path) return new_conf
python
def set_main(key, value, path=MAIN_CF): ''' Set a single config value in the main.cf file. If the value does not already exist, it will be appended to the end. CLI Example: salt <minion> postfix.set_main mailq_path /usr/bin/mailq ''' pairs, conf_list = _parse_main(path) new_conf = [] key_line_match = re.compile("^{0}([\\s=]|$)".format(re.escape(key))) if key in pairs: for line in conf_list: if re.match(key_line_match, line): new_conf.append('{0} = {1}'.format(key, value)) else: new_conf.append(line) else: conf_list.append('{0} = {1}'.format(key, value)) new_conf = conf_list _write_conf(new_conf, path) return new_conf
[ "def", "set_main", "(", "key", ",", "value", ",", "path", "=", "MAIN_CF", ")", ":", "pairs", ",", "conf_list", "=", "_parse_main", "(", "path", ")", "new_conf", "=", "[", "]", "key_line_match", "=", "re", ".", "compile", "(", "\"^{0}([\\\\s=]|$)\"", ".",...
Set a single config value in the main.cf file. If the value does not already exist, it will be appended to the end. CLI Example: salt <minion> postfix.set_main mailq_path /usr/bin/mailq
[ "Set", "a", "single", "config", "value", "in", "the", "main", ".", "cf", "file", ".", "If", "the", "value", "does", "not", "already", "exist", "it", "will", "be", "appended", "to", "the", "end", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L284-L308
train
saltstack/salt
salt/modules/postfix.py
_write_conf
def _write_conf(conf, path=MAIN_CF): ''' Write out configuration file. ''' with salt.utils.files.fopen(path, 'w') as fh_: for line in conf: line = salt.utils.stringutils.to_str(line) if isinstance(line, dict): fh_.write(' '.join(line)) else: fh_.write(line) fh_.write('\n')
python
def _write_conf(conf, path=MAIN_CF): ''' Write out configuration file. ''' with salt.utils.files.fopen(path, 'w') as fh_: for line in conf: line = salt.utils.stringutils.to_str(line) if isinstance(line, dict): fh_.write(' '.join(line)) else: fh_.write(line) fh_.write('\n')
[ "def", "_write_conf", "(", "conf", ",", "path", "=", "MAIN_CF", ")", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'w'", ")", "as", "fh_", ":", "for", "line", "in", "conf", ":", "line", "=", "salt", ".", "utils...
Write out configuration file.
[ "Write", "out", "configuration", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L311-L322
train
saltstack/salt
salt/modules/postfix.py
show_queue
def show_queue(): ''' Show contents of the mail queue CLI Example: .. code-block:: bash salt '*' postfix.show_queue ''' cmd = 'mailq' out = __salt__['cmd.run'](cmd).splitlines() queue = [] queue_pattern = re.compile(r"(?P<queue_id>^[A-Z0-9]+)\s+(?P<size>\d+)\s(?P<timestamp>\w{3}\s\w{3}\s\d{1,2}\s\d{2}\:\d{2}\:\d{2})\s+(?P<sender>.+)") recipient_pattern = re.compile(r"^\s+(?P<recipient>.+)") for line in out: if re.match('^[-|postqueue:|Mail]', line): # discard in-queue wrapper continue if re.match(queue_pattern, line): m = re.match(queue_pattern, line) queue_id = m.group('queue_id') size = m.group('size') timestamp = m.group('timestamp') sender = m.group('sender') elif re.match(recipient_pattern, line): # recipient/s m = re.match(recipient_pattern, line) recipient = m.group('recipient') elif not line: # end of record queue.append({'queue_id': queue_id, 'size': size, 'timestamp': timestamp, 'sender': sender, 'recipient': recipient}) return queue
python
def show_queue(): ''' Show contents of the mail queue CLI Example: .. code-block:: bash salt '*' postfix.show_queue ''' cmd = 'mailq' out = __salt__['cmd.run'](cmd).splitlines() queue = [] queue_pattern = re.compile(r"(?P<queue_id>^[A-Z0-9]+)\s+(?P<size>\d+)\s(?P<timestamp>\w{3}\s\w{3}\s\d{1,2}\s\d{2}\:\d{2}\:\d{2})\s+(?P<sender>.+)") recipient_pattern = re.compile(r"^\s+(?P<recipient>.+)") for line in out: if re.match('^[-|postqueue:|Mail]', line): # discard in-queue wrapper continue if re.match(queue_pattern, line): m = re.match(queue_pattern, line) queue_id = m.group('queue_id') size = m.group('size') timestamp = m.group('timestamp') sender = m.group('sender') elif re.match(recipient_pattern, line): # recipient/s m = re.match(recipient_pattern, line) recipient = m.group('recipient') elif not line: # end of record queue.append({'queue_id': queue_id, 'size': size, 'timestamp': timestamp, 'sender': sender, 'recipient': recipient}) return queue
[ "def", "show_queue", "(", ")", ":", "cmd", "=", "'mailq'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", ".", "splitlines", "(", ")", "queue", "=", "[", "]", "queue_pattern", "=", "re", ".", "compile", "(", "r\"(?P<queue_id>^[A-Z0-9]+)\...
Show contents of the mail queue CLI Example: .. code-block:: bash salt '*' postfix.show_queue
[ "Show", "contents", "of", "the", "mail", "queue" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L325-L357
train
saltstack/salt
salt/modules/postfix.py
delete
def delete(queue_id): ''' Delete message(s) from the mail queue CLI Example: .. code-block:: bash salt '*' postfix.delete 5C33CA0DEA salt '*' postfix.delete ALL ''' ret = {'message': '', 'result': True } if not queue_id: log.error('Require argument queue_id') if not queue_id == 'ALL': queue = show_queue() _message = None for item in queue: if item['queue_id'] == queue_id: _message = item if not _message: ret['message'] = 'No message in queue with ID {0}'.format(queue_id) ret['result'] = False return ret cmd = 'postsuper -d {0}'.format(queue_id) result = __salt__['cmd.run_all'](cmd) if result['retcode'] == 0: if queue_id == 'ALL': ret['message'] = 'Successfully removed all messages' else: ret['message'] = 'Successfully removed message with queue id {0}'.format(queue_id) else: if queue_id == 'ALL': ret['message'] = 'Unable to removed all messages' else: ret['message'] = 'Unable to remove message with queue id {0}: {1}'.format(queue_id, result['stderr']) return ret
python
def delete(queue_id): ''' Delete message(s) from the mail queue CLI Example: .. code-block:: bash salt '*' postfix.delete 5C33CA0DEA salt '*' postfix.delete ALL ''' ret = {'message': '', 'result': True } if not queue_id: log.error('Require argument queue_id') if not queue_id == 'ALL': queue = show_queue() _message = None for item in queue: if item['queue_id'] == queue_id: _message = item if not _message: ret['message'] = 'No message in queue with ID {0}'.format(queue_id) ret['result'] = False return ret cmd = 'postsuper -d {0}'.format(queue_id) result = __salt__['cmd.run_all'](cmd) if result['retcode'] == 0: if queue_id == 'ALL': ret['message'] = 'Successfully removed all messages' else: ret['message'] = 'Successfully removed message with queue id {0}'.format(queue_id) else: if queue_id == 'ALL': ret['message'] = 'Unable to removed all messages' else: ret['message'] = 'Unable to remove message with queue id {0}: {1}'.format(queue_id, result['stderr']) return ret
[ "def", "delete", "(", "queue_id", ")", ":", "ret", "=", "{", "'message'", ":", "''", ",", "'result'", ":", "True", "}", "if", "not", "queue_id", ":", "log", ".", "error", "(", "'Require argument queue_id'", ")", "if", "not", "queue_id", "==", "'ALL'", ...
Delete message(s) from the mail queue CLI Example: .. code-block:: bash salt '*' postfix.delete 5C33CA0DEA salt '*' postfix.delete ALL
[ "Delete", "message", "(", "s", ")", "from", "the", "mail", "queue" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L360-L406
train
saltstack/salt
salt/modules/solrcloud.py
collection_get_options
def collection_get_options(collection_name, **kwargs): ''' Get collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query CLI Example: .. code-block:: bash salt '*' solrcloud.collection_get_options collection_name ''' cluster = cluster_status(**kwargs) options = { "collection.configName": cluster["collections"][collection_name]["configName"], "router.name": cluster["collections"][collection_name]["router"]["name"], "replicationFactor": int(cluster["collections"][collection_name]["replicationFactor"]), "maxShardsPerNode": int(cluster["collections"][collection_name]["maxShardsPerNode"]), "autoAddReplicas": cluster["collections"][collection_name]["autoAddReplicas"] is True } if 'rule' in cluster["collections"][collection_name]: options['rule'] = cluster["collections"][collection_name]['rule'] if 'snitch' in cluster["collections"][collection_name]: options['snitch'] = cluster["collections"][collection_name]['rule'] return options
python
def collection_get_options(collection_name, **kwargs): ''' Get collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query CLI Example: .. code-block:: bash salt '*' solrcloud.collection_get_options collection_name ''' cluster = cluster_status(**kwargs) options = { "collection.configName": cluster["collections"][collection_name]["configName"], "router.name": cluster["collections"][collection_name]["router"]["name"], "replicationFactor": int(cluster["collections"][collection_name]["replicationFactor"]), "maxShardsPerNode": int(cluster["collections"][collection_name]["maxShardsPerNode"]), "autoAddReplicas": cluster["collections"][collection_name]["autoAddReplicas"] is True } if 'rule' in cluster["collections"][collection_name]: options['rule'] = cluster["collections"][collection_name]['rule'] if 'snitch' in cluster["collections"][collection_name]: options['snitch'] = cluster["collections"][collection_name]['rule'] return options
[ "def", "collection_get_options", "(", "collection_name", ",", "*", "*", "kwargs", ")", ":", "cluster", "=", "cluster_status", "(", "*", "*", "kwargs", ")", "options", "=", "{", "\"collection.configName\"", ":", "cluster", "[", "\"collections\"", "]", "[", "col...
Get collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query CLI Example: .. code-block:: bash salt '*' solrcloud.collection_get_options collection_name
[ "Get", "collection", "options" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solrcloud.py#L445-L473
train
saltstack/salt
salt/modules/solrcloud.py
collection_set_options
def collection_set_options(collection_name, options, **kwargs): ''' Change collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query Note that not every parameter can be changed after collection creation CLI Example: .. code-block:: bash salt '*' solrcloud.collection_set_options collection_name options={"replicationFactor":4} ''' for option in list(options.keys()): if option not in CREATION_ONLY_OPTION: raise ValueError('Option '+option+' can\'t be modified after collection creation.') options_string = _validate_collection_options(options) _query('admin/collections?action=MODIFYCOLLECTION&wt=json&collection='+collection_name+options_string, **kwargs)
python
def collection_set_options(collection_name, options, **kwargs): ''' Change collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query Note that not every parameter can be changed after collection creation CLI Example: .. code-block:: bash salt '*' solrcloud.collection_set_options collection_name options={"replicationFactor":4} ''' for option in list(options.keys()): if option not in CREATION_ONLY_OPTION: raise ValueError('Option '+option+' can\'t be modified after collection creation.') options_string = _validate_collection_options(options) _query('admin/collections?action=MODIFYCOLLECTION&wt=json&collection='+collection_name+options_string, **kwargs)
[ "def", "collection_set_options", "(", "collection_name", ",", "options", ",", "*", "*", "kwargs", ")", ":", "for", "option", "in", "list", "(", "options", ".", "keys", "(", ")", ")", ":", "if", "option", "not", "in", "CREATION_ONLY_OPTION", ":", "raise", ...
Change collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query Note that not every parameter can be changed after collection creation CLI Example: .. code-block:: bash salt '*' solrcloud.collection_set_options collection_name options={"replicationFactor":4}
[ "Change", "collection", "options" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solrcloud.py#L476-L497
train
saltstack/salt
salt/modules/keystore.py
list
def list(keystore, passphrase, alias=None, return_cert=False): ''' Lists certificates in a keytool managed keystore. :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore :param alias: (Optional) If found, displays details on only this key :param return_certs: (Optional) Also return certificate PEM. .. warning:: There are security implications for using return_cert to return decrypted certificates. CLI Example: .. code-block:: bash salt '*' keystore.list /usr/lib/jvm/java-8/jre/lib/security/cacerts changeit salt '*' keystore.list /usr/lib/jvm/java-8/jre/lib/security/cacerts changeit debian:verisign_-_g5.pem ''' ASN1 = OpenSSL.crypto.FILETYPE_ASN1 PEM = OpenSSL.crypto.FILETYPE_PEM decoded_certs = [] entries = [] keystore = jks.KeyStore.load(keystore, passphrase) if alias: # If alias is given, look it up and build expected data structure entry_value = keystore.entries.get(alias) if entry_value: entries = [(alias, entry_value)] else: entries = keystore.entries.items() if entries: for entry_alias, cert_enc in entries: entry_data = {} if isinstance(cert_enc, jks.PrivateKeyEntry): cert_result = cert_enc.cert_chain[0][1] entry_data['type'] = 'PrivateKeyEntry' elif isinstance(cert_enc, jks.TrustedCertEntry): cert_result = cert_enc.cert entry_data['type'] = 'TrustedCertEntry' else: raise CommandExecutionError('Unsupported EntryType detected in keystore') # Detect if ASN1 binary, otherwise assume PEM if '\x30' in cert_result[0]: public_cert = OpenSSL.crypto.load_certificate(ASN1, cert_result) else: public_cert = OpenSSL.crypto.load_certificate(PEM, cert_result) entry_data.update(_parse_cert(entry_alias, public_cert, return_cert)) decoded_certs.append(entry_data) return decoded_certs
python
def list(keystore, passphrase, alias=None, return_cert=False): ''' Lists certificates in a keytool managed keystore. :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore :param alias: (Optional) If found, displays details on only this key :param return_certs: (Optional) Also return certificate PEM. .. warning:: There are security implications for using return_cert to return decrypted certificates. CLI Example: .. code-block:: bash salt '*' keystore.list /usr/lib/jvm/java-8/jre/lib/security/cacerts changeit salt '*' keystore.list /usr/lib/jvm/java-8/jre/lib/security/cacerts changeit debian:verisign_-_g5.pem ''' ASN1 = OpenSSL.crypto.FILETYPE_ASN1 PEM = OpenSSL.crypto.FILETYPE_PEM decoded_certs = [] entries = [] keystore = jks.KeyStore.load(keystore, passphrase) if alias: # If alias is given, look it up and build expected data structure entry_value = keystore.entries.get(alias) if entry_value: entries = [(alias, entry_value)] else: entries = keystore.entries.items() if entries: for entry_alias, cert_enc in entries: entry_data = {} if isinstance(cert_enc, jks.PrivateKeyEntry): cert_result = cert_enc.cert_chain[0][1] entry_data['type'] = 'PrivateKeyEntry' elif isinstance(cert_enc, jks.TrustedCertEntry): cert_result = cert_enc.cert entry_data['type'] = 'TrustedCertEntry' else: raise CommandExecutionError('Unsupported EntryType detected in keystore') # Detect if ASN1 binary, otherwise assume PEM if '\x30' in cert_result[0]: public_cert = OpenSSL.crypto.load_certificate(ASN1, cert_result) else: public_cert = OpenSSL.crypto.load_certificate(PEM, cert_result) entry_data.update(_parse_cert(entry_alias, public_cert, return_cert)) decoded_certs.append(entry_data) return decoded_certs
[ "def", "list", "(", "keystore", ",", "passphrase", ",", "alias", "=", "None", ",", "return_cert", "=", "False", ")", ":", "ASN1", "=", "OpenSSL", ".", "crypto", ".", "FILETYPE_ASN1", "PEM", "=", "OpenSSL", ".", "crypto", ".", "FILETYPE_PEM", "decoded_certs...
Lists certificates in a keytool managed keystore. :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore :param alias: (Optional) If found, displays details on only this key :param return_certs: (Optional) Also return certificate PEM. .. warning:: There are security implications for using return_cert to return decrypted certificates. CLI Example: .. code-block:: bash salt '*' keystore.list /usr/lib/jvm/java-8/jre/lib/security/cacerts changeit salt '*' keystore.list /usr/lib/jvm/java-8/jre/lib/security/cacerts changeit debian:verisign_-_g5.pem
[ "Lists", "certificates", "in", "a", "keytool", "managed", "keystore", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystore.py#L63-L121
train
saltstack/salt
salt/modules/keystore.py
add
def add(name, keystore, passphrase, certificate, private_key=None): ''' Adds certificates to an existing keystore or creates a new one if necesssary. :param name: alias for the certificate :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore :param certificate: The PEM public certificate to add to keystore. Can be a string for file. :param private_key: (Optional for TrustedCert) The PEM private key to add to the keystore CLI Example: .. code-block:: bash salt '*' keystore.add aliasname /tmp/test.store changeit /tmp/testcert.crt salt '*' keystore.add aliasname /tmp/test.store changeit certificate="-----BEGIN CERTIFICATE-----SIb...BM=-----END CERTIFICATE-----" salt '*' keystore.add keyname /tmp/test.store changeit /tmp/512.cert private_key=/tmp/512.key ''' ASN1 = OpenSSL.crypto.FILETYPE_ASN1 PEM = OpenSSL.crypto.FILETYPE_PEM certs_list = [] if os.path.isfile(keystore): keystore_object = jks.KeyStore.load(keystore, passphrase) for alias, loaded_cert in keystore_object.entries.items(): certs_list.append(loaded_cert) try: cert_string = __salt__['x509.get_pem_entry'](certificate) except SaltInvocationError: raise SaltInvocationError('Invalid certificate file or string: {0}'.format(certificate)) if private_key: # Accept PEM input format, but convert to DES for loading into new keystore key_string = __salt__['x509.get_pem_entry'](private_key) loaded_cert = OpenSSL.crypto.load_certificate(PEM, cert_string) loaded_key = OpenSSL.crypto.load_privatekey(PEM, key_string) dumped_cert = OpenSSL.crypto.dump_certificate(ASN1, loaded_cert) dumped_key = OpenSSL.crypto.dump_privatekey(ASN1, loaded_key) new_entry = jks.PrivateKeyEntry.new(name, [dumped_cert], dumped_key, 'rsa_raw') else: new_entry = jks.TrustedCertEntry.new(name, cert_string) certs_list.append(new_entry) keystore_object = jks.KeyStore.new('jks', certs_list) keystore_object.save(keystore, passphrase) return True
python
def add(name, keystore, passphrase, certificate, private_key=None): ''' Adds certificates to an existing keystore or creates a new one if necesssary. :param name: alias for the certificate :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore :param certificate: The PEM public certificate to add to keystore. Can be a string for file. :param private_key: (Optional for TrustedCert) The PEM private key to add to the keystore CLI Example: .. code-block:: bash salt '*' keystore.add aliasname /tmp/test.store changeit /tmp/testcert.crt salt '*' keystore.add aliasname /tmp/test.store changeit certificate="-----BEGIN CERTIFICATE-----SIb...BM=-----END CERTIFICATE-----" salt '*' keystore.add keyname /tmp/test.store changeit /tmp/512.cert private_key=/tmp/512.key ''' ASN1 = OpenSSL.crypto.FILETYPE_ASN1 PEM = OpenSSL.crypto.FILETYPE_PEM certs_list = [] if os.path.isfile(keystore): keystore_object = jks.KeyStore.load(keystore, passphrase) for alias, loaded_cert in keystore_object.entries.items(): certs_list.append(loaded_cert) try: cert_string = __salt__['x509.get_pem_entry'](certificate) except SaltInvocationError: raise SaltInvocationError('Invalid certificate file or string: {0}'.format(certificate)) if private_key: # Accept PEM input format, but convert to DES for loading into new keystore key_string = __salt__['x509.get_pem_entry'](private_key) loaded_cert = OpenSSL.crypto.load_certificate(PEM, cert_string) loaded_key = OpenSSL.crypto.load_privatekey(PEM, key_string) dumped_cert = OpenSSL.crypto.dump_certificate(ASN1, loaded_cert) dumped_key = OpenSSL.crypto.dump_privatekey(ASN1, loaded_key) new_entry = jks.PrivateKeyEntry.new(name, [dumped_cert], dumped_key, 'rsa_raw') else: new_entry = jks.TrustedCertEntry.new(name, cert_string) certs_list.append(new_entry) keystore_object = jks.KeyStore.new('jks', certs_list) keystore_object.save(keystore, passphrase) return True
[ "def", "add", "(", "name", ",", "keystore", ",", "passphrase", ",", "certificate", ",", "private_key", "=", "None", ")", ":", "ASN1", "=", "OpenSSL", ".", "crypto", ".", "FILETYPE_ASN1", "PEM", "=", "OpenSSL", ".", "crypto", ".", "FILETYPE_PEM", "certs_lis...
Adds certificates to an existing keystore or creates a new one if necesssary. :param name: alias for the certificate :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore :param certificate: The PEM public certificate to add to keystore. Can be a string for file. :param private_key: (Optional for TrustedCert) The PEM private key to add to the keystore CLI Example: .. code-block:: bash salt '*' keystore.add aliasname /tmp/test.store changeit /tmp/testcert.crt salt '*' keystore.add aliasname /tmp/test.store changeit certificate="-----BEGIN CERTIFICATE-----SIb...BM=-----END CERTIFICATE-----" salt '*' keystore.add keyname /tmp/test.store changeit /tmp/512.cert private_key=/tmp/512.key
[ "Adds", "certificates", "to", "an", "existing", "keystore", "or", "creates", "a", "new", "one", "if", "necesssary", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystore.py#L124-L172
train
saltstack/salt
salt/modules/keystore.py
remove
def remove(name, keystore, passphrase): ''' Removes a certificate from an existing keystore. Returns True if remove was successful, otherwise False :param name: alias for the certificate :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore CLI Example: .. code-block:: bash salt '*' keystore.remove aliasname /tmp/test.store changeit ''' certs_list = [] keystore_object = jks.KeyStore.load(keystore, passphrase) for alias, loaded_cert in keystore_object.entries.items(): if name not in alias: certs_list.append(loaded_cert) if len(keystore_object.entries) != len(certs_list): # Entry has been removed, save keystore updates keystore_object = jks.KeyStore.new('jks', certs_list) keystore_object.save(keystore, passphrase) return True else: # No alias found, notify user return False
python
def remove(name, keystore, passphrase): ''' Removes a certificate from an existing keystore. Returns True if remove was successful, otherwise False :param name: alias for the certificate :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore CLI Example: .. code-block:: bash salt '*' keystore.remove aliasname /tmp/test.store changeit ''' certs_list = [] keystore_object = jks.KeyStore.load(keystore, passphrase) for alias, loaded_cert in keystore_object.entries.items(): if name not in alias: certs_list.append(loaded_cert) if len(keystore_object.entries) != len(certs_list): # Entry has been removed, save keystore updates keystore_object = jks.KeyStore.new('jks', certs_list) keystore_object.save(keystore, passphrase) return True else: # No alias found, notify user return False
[ "def", "remove", "(", "name", ",", "keystore", ",", "passphrase", ")", ":", "certs_list", "=", "[", "]", "keystore_object", "=", "jks", ".", "KeyStore", ".", "load", "(", "keystore", ",", "passphrase", ")", "for", "alias", ",", "loaded_cert", "in", "keys...
Removes a certificate from an existing keystore. Returns True if remove was successful, otherwise False :param name: alias for the certificate :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore CLI Example: .. code-block:: bash salt '*' keystore.remove aliasname /tmp/test.store changeit
[ "Removes", "a", "certificate", "from", "an", "existing", "keystore", ".", "Returns", "True", "if", "remove", "was", "successful", "otherwise", "False" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystore.py#L175-L203
train
saltstack/salt
salt/cache/localfs.py
store
def store(bank, key, data, cachedir): ''' Store information in a file. ''' base = os.path.join(cachedir, os.path.normpath(bank)) try: os.makedirs(base) except OSError as exc: if exc.errno != errno.EEXIST: raise SaltCacheError( 'The cache directory, {0}, could not be created: {1}'.format( base, exc ) ) outfile = os.path.join(base, '{0}.p'.format(key)) tmpfh, tmpfname = tempfile.mkstemp(dir=base) os.close(tmpfh) try: with salt.utils.files.fopen(tmpfname, 'w+b') as fh_: fh_.write(__context__['serial'].dumps(data)) # On Windows, os.rename will fail if the destination file exists. salt.utils.atomicfile.atomic_rename(tmpfname, outfile) except IOError as exc: raise SaltCacheError( 'There was an error writing the cache file, {0}: {1}'.format( base, exc ) )
python
def store(bank, key, data, cachedir): ''' Store information in a file. ''' base = os.path.join(cachedir, os.path.normpath(bank)) try: os.makedirs(base) except OSError as exc: if exc.errno != errno.EEXIST: raise SaltCacheError( 'The cache directory, {0}, could not be created: {1}'.format( base, exc ) ) outfile = os.path.join(base, '{0}.p'.format(key)) tmpfh, tmpfname = tempfile.mkstemp(dir=base) os.close(tmpfh) try: with salt.utils.files.fopen(tmpfname, 'w+b') as fh_: fh_.write(__context__['serial'].dumps(data)) # On Windows, os.rename will fail if the destination file exists. salt.utils.atomicfile.atomic_rename(tmpfname, outfile) except IOError as exc: raise SaltCacheError( 'There was an error writing the cache file, {0}: {1}'.format( base, exc ) )
[ "def", "store", "(", "bank", ",", "key", ",", "data", ",", "cachedir", ")", ":", "base", "=", "os", ".", "path", ".", "join", "(", "cachedir", ",", "os", ".", "path", ".", "normpath", "(", "bank", ")", ")", "try", ":", "os", ".", "makedirs", "(...
Store information in a file.
[ "Store", "information", "in", "a", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/localfs.py#L44-L72
train
saltstack/salt
salt/cache/localfs.py
fetch
def fetch(bank, key, cachedir): ''' Fetch information from a file. ''' inkey = False key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) if not os.path.isfile(key_file): # The bank includes the full filename, and the key is inside the file key_file = os.path.join(cachedir, os.path.normpath(bank) + '.p') inkey = True if not os.path.isfile(key_file): log.debug('Cache file "%s" does not exist', key_file) return {} try: with salt.utils.files.fopen(key_file, 'rb') as fh_: if inkey: return __context__['serial'].load(fh_)[key] else: return __context__['serial'].load(fh_) except IOError as exc: raise SaltCacheError( 'There was an error reading the cache file "{0}": {1}'.format( key_file, exc ) )
python
def fetch(bank, key, cachedir): ''' Fetch information from a file. ''' inkey = False key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) if not os.path.isfile(key_file): # The bank includes the full filename, and the key is inside the file key_file = os.path.join(cachedir, os.path.normpath(bank) + '.p') inkey = True if not os.path.isfile(key_file): log.debug('Cache file "%s" does not exist', key_file) return {} try: with salt.utils.files.fopen(key_file, 'rb') as fh_: if inkey: return __context__['serial'].load(fh_)[key] else: return __context__['serial'].load(fh_) except IOError as exc: raise SaltCacheError( 'There was an error reading the cache file "{0}": {1}'.format( key_file, exc ) )
[ "def", "fetch", "(", "bank", ",", "key", ",", "cachedir", ")", ":", "inkey", "=", "False", "key_file", "=", "os", ".", "path", ".", "join", "(", "cachedir", ",", "os", ".", "path", ".", "normpath", "(", "bank", ")", ",", "'{0}.p'", ".", "format", ...
Fetch information from a file.
[ "Fetch", "information", "from", "a", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/localfs.py#L75-L100
train