repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/portage_config.py
get_flags_from_package_conf
def get_flags_from_package_conf(conf, atom): ''' Get flags for a given package or DEPEND atom. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.get_flags_from_package_conf license salt ''' if conf in SUPPORTED_CONFS: package_file = _get_config_file(conf, atom) if '/' not in atom: atom = _p_to_cp(atom) has_wildcard = '*' in atom if has_wildcard: match_list = set(atom) else: try: match_list = set(_porttree().dbapi.xmatch("match-all", atom)) except AttributeError: return [] flags = [] try: with salt.utils.files.fopen(package_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line).strip() line_package = line.split()[0] if has_wildcard: found_match = line_package == atom else: line_list = _porttree().dbapi.xmatch("match-all", line_package) found_match = match_list.issubset(line_list) if found_match: f_tmp = [flag for flag in line.strip().split(' ') if flag][1:] if f_tmp: flags.extend(f_tmp) else: flags.append('~ARCH') return _merge_flags(flags) except IOError: return []
python
def get_flags_from_package_conf(conf, atom): ''' Get flags for a given package or DEPEND atom. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.get_flags_from_package_conf license salt ''' if conf in SUPPORTED_CONFS: package_file = _get_config_file(conf, atom) if '/' not in atom: atom = _p_to_cp(atom) has_wildcard = '*' in atom if has_wildcard: match_list = set(atom) else: try: match_list = set(_porttree().dbapi.xmatch("match-all", atom)) except AttributeError: return [] flags = [] try: with salt.utils.files.fopen(package_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line).strip() line_package = line.split()[0] if has_wildcard: found_match = line_package == atom else: line_list = _porttree().dbapi.xmatch("match-all", line_package) found_match = match_list.issubset(line_list) if found_match: f_tmp = [flag for flag in line.strip().split(' ') if flag][1:] if f_tmp: flags.extend(f_tmp) else: flags.append('~ARCH') return _merge_flags(flags) except IOError: return []
[ "def", "get_flags_from_package_conf", "(", "conf", ",", "atom", ")", ":", "if", "conf", "in", "SUPPORTED_CONFS", ":", "package_file", "=", "_get_config_file", "(", "conf", ",", "atom", ")", "if", "'/'", "not", "in", "atom", ":", "atom", "=", "_p_to_cp", "(...
Get flags for a given package or DEPEND atom. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.get_flags_from_package_conf license salt
[ "Get", "flags", "for", "a", "given", "package", "or", "DEPEND", "atom", ".", "Warning", ":", "This", "only", "works", "if", "the", "configuration", "files", "tree", "is", "in", "the", "correct", "format", "(", "the", "one", "enforced", "by", "enforce_nice_...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L459-L507
train
saltstack/salt
salt/modules/portage_config.py
has_flag
def has_flag(conf, atom, flag): ''' Verify if the given package or DEPEND atom has the given flag. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.has_flag license salt Apache-2.0 ''' if flag in get_flags_from_package_conf(conf, atom): return True return False
python
def has_flag(conf, atom, flag): ''' Verify if the given package or DEPEND atom has the given flag. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.has_flag license salt Apache-2.0 ''' if flag in get_flags_from_package_conf(conf, atom): return True return False
[ "def", "has_flag", "(", "conf", ",", "atom", ",", "flag", ")", ":", "if", "flag", "in", "get_flags_from_package_conf", "(", "conf", ",", "atom", ")", ":", "return", "True", "return", "False" ]
Verify if the given package or DEPEND atom has the given flag. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.has_flag license salt Apache-2.0
[ "Verify", "if", "the", "given", "package", "or", "DEPEND", "atom", "has", "the", "given", "flag", ".", "Warning", ":", "This", "only", "works", "if", "the", "configuration", "files", "tree", "is", "in", "the", "correct", "format", "(", "the", "one", "enf...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L510-L524
train
saltstack/salt
salt/modules/portage_config.py
get_missing_flags
def get_missing_flags(conf, atom, flags): ''' Find out which of the given flags are currently not set. CLI Example: .. code-block:: bash salt '*' portage_config.get_missing_flags use salt "['ldap', '-libvirt', 'openssl']" ''' new_flags = [] for flag in flags: if not has_flag(conf, atom, flag): new_flags.append(flag) return new_flags
python
def get_missing_flags(conf, atom, flags): ''' Find out which of the given flags are currently not set. CLI Example: .. code-block:: bash salt '*' portage_config.get_missing_flags use salt "['ldap', '-libvirt', 'openssl']" ''' new_flags = [] for flag in flags: if not has_flag(conf, atom, flag): new_flags.append(flag) return new_flags
[ "def", "get_missing_flags", "(", "conf", ",", "atom", ",", "flags", ")", ":", "new_flags", "=", "[", "]", "for", "flag", "in", "flags", ":", "if", "not", "has_flag", "(", "conf", ",", "atom", ",", "flag", ")", ":", "new_flags", ".", "append", "(", ...
Find out which of the given flags are currently not set. CLI Example: .. code-block:: bash salt '*' portage_config.get_missing_flags use salt "['ldap', '-libvirt', 'openssl']"
[ "Find", "out", "which", "of", "the", "given", "flags", "are", "currently", "not", "set", ".", "CLI", "Example", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L527-L540
train
saltstack/salt
salt/modules/portage_config.py
is_present
def is_present(conf, atom): ''' Tell if a given package or DEPEND atom is present in the configuration files tree. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.is_present unmask salt ''' if conf in SUPPORTED_CONFS: if not isinstance(atom, portage.dep.Atom): atom = portage.dep.Atom(atom, allow_wildcard=True) has_wildcard = '*' in atom package_file = _get_config_file(conf, six.text_type(atom)) # wildcards are valid in confs if has_wildcard: match_list = set(atom) else: match_list = set(_porttree().dbapi.xmatch("match-all", atom)) try: with salt.utils.files.fopen(package_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line).strip() line_package = line.split()[0] if has_wildcard: if line_package == six.text_type(atom): return True else: line_list = _porttree().dbapi.xmatch("match-all", line_package) if match_list.issubset(line_list): return True except IOError: pass return False
python
def is_present(conf, atom): ''' Tell if a given package or DEPEND atom is present in the configuration files tree. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.is_present unmask salt ''' if conf in SUPPORTED_CONFS: if not isinstance(atom, portage.dep.Atom): atom = portage.dep.Atom(atom, allow_wildcard=True) has_wildcard = '*' in atom package_file = _get_config_file(conf, six.text_type(atom)) # wildcards are valid in confs if has_wildcard: match_list = set(atom) else: match_list = set(_porttree().dbapi.xmatch("match-all", atom)) try: with salt.utils.files.fopen(package_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line).strip() line_package = line.split()[0] if has_wildcard: if line_package == six.text_type(atom): return True else: line_list = _porttree().dbapi.xmatch("match-all", line_package) if match_list.issubset(line_list): return True except IOError: pass return False
[ "def", "is_present", "(", "conf", ",", "atom", ")", ":", "if", "conf", "in", "SUPPORTED_CONFS", ":", "if", "not", "isinstance", "(", "atom", ",", "portage", ".", "dep", ".", "Atom", ")", ":", "atom", "=", "portage", ".", "dep", ".", "Atom", "(", "a...
Tell if a given package or DEPEND atom is present in the configuration files tree. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*' portage_config.is_present unmask salt
[ "Tell", "if", "a", "given", "package", "or", "DEPEND", "atom", "is", "present", "in", "the", "configuration", "files", "tree", ".", "Warning", ":", "This", "only", "works", "if", "the", "configuration", "files", "tree", "is", "in", "the", "correct", "forma...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L558-L599
train
saltstack/salt
salt/modules/portage_config.py
get_iuse
def get_iuse(cp): ''' .. versionadded:: 2015.8.0 Gets the current IUSE flags from the tree. @type: cpv: string @param cpv: cat/pkg @rtype list @returns [] or the list of IUSE flags ''' cpv = _get_cpv(cp) try: # aux_get might return dupes, so run them through set() to remove them dirty_flags = _porttree().dbapi.aux_get(cpv, ["IUSE"])[0].split() return list(set(dirty_flags)) except Exception as e: return []
python
def get_iuse(cp): ''' .. versionadded:: 2015.8.0 Gets the current IUSE flags from the tree. @type: cpv: string @param cpv: cat/pkg @rtype list @returns [] or the list of IUSE flags ''' cpv = _get_cpv(cp) try: # aux_get might return dupes, so run them through set() to remove them dirty_flags = _porttree().dbapi.aux_get(cpv, ["IUSE"])[0].split() return list(set(dirty_flags)) except Exception as e: return []
[ "def", "get_iuse", "(", "cp", ")", ":", "cpv", "=", "_get_cpv", "(", "cp", ")", "try", ":", "# aux_get might return dupes, so run them through set() to remove them", "dirty_flags", "=", "_porttree", "(", ")", ".", "dbapi", ".", "aux_get", "(", "cpv", ",", "[", ...
.. versionadded:: 2015.8.0 Gets the current IUSE flags from the tree. @type: cpv: string @param cpv: cat/pkg @rtype list @returns [] or the list of IUSE flags
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L602-L619
train
saltstack/salt
salt/modules/portage_config.py
get_installed_use
def get_installed_use(cp, use="USE"): ''' .. versionadded:: 2015.8.0 Gets the installed USE flags from the VARDB. @type: cp: string @param cp: cat/pkg @type use: string @param use: 1 of ["USE", "PKGUSE"] @rtype list @returns [] or the list of IUSE flags ''' portage = _get_portage() cpv = _get_cpv(cp) return portage.db[portage.root]["vartree"].dbapi.aux_get(cpv, [use])[0].split()
python
def get_installed_use(cp, use="USE"): ''' .. versionadded:: 2015.8.0 Gets the installed USE flags from the VARDB. @type: cp: string @param cp: cat/pkg @type use: string @param use: 1 of ["USE", "PKGUSE"] @rtype list @returns [] or the list of IUSE flags ''' portage = _get_portage() cpv = _get_cpv(cp) return portage.db[portage.root]["vartree"].dbapi.aux_get(cpv, [use])[0].split()
[ "def", "get_installed_use", "(", "cp", ",", "use", "=", "\"USE\"", ")", ":", "portage", "=", "_get_portage", "(", ")", "cpv", "=", "_get_cpv", "(", "cp", ")", "return", "portage", ".", "db", "[", "portage", ".", "root", "]", "[", "\"vartree\"", "]", ...
.. versionadded:: 2015.8.0 Gets the installed USE flags from the VARDB. @type: cp: string @param cp: cat/pkg @type use: string @param use: 1 of ["USE", "PKGUSE"] @rtype list @returns [] or the list of IUSE flags
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L622-L637
train
saltstack/salt
salt/modules/portage_config.py
filter_flags
def filter_flags(use, use_expand_hidden, usemasked, useforced): ''' .. versionadded:: 2015.8.0 Filter function to remove hidden or otherwise not normally visible USE flags from a list. @type use: list @param use: the USE flag list to be filtered. @type use_expand_hidden: list @param use_expand_hidden: list of flags hidden. @type usemasked: list @param usemasked: list of masked USE flags. @type useforced: list @param useforced: the forced USE flags. @rtype: list @return the filtered USE flags. ''' portage = _get_portage() # clean out some environment flags, since they will most probably # be confusing for the user for f in use_expand_hidden: f = f.lower()+ "_" for x in use: if f in x: use.remove(x) # clean out any arch's archlist = portage.settings["PORTAGE_ARCHLIST"].split() for a in use[:]: if a in archlist: use.remove(a) # dbl check if any from usemasked or useforced are still there masked = usemasked + useforced for a in use[:]: if a in masked: use.remove(a) return use
python
def filter_flags(use, use_expand_hidden, usemasked, useforced): ''' .. versionadded:: 2015.8.0 Filter function to remove hidden or otherwise not normally visible USE flags from a list. @type use: list @param use: the USE flag list to be filtered. @type use_expand_hidden: list @param use_expand_hidden: list of flags hidden. @type usemasked: list @param usemasked: list of masked USE flags. @type useforced: list @param useforced: the forced USE flags. @rtype: list @return the filtered USE flags. ''' portage = _get_portage() # clean out some environment flags, since they will most probably # be confusing for the user for f in use_expand_hidden: f = f.lower()+ "_" for x in use: if f in x: use.remove(x) # clean out any arch's archlist = portage.settings["PORTAGE_ARCHLIST"].split() for a in use[:]: if a in archlist: use.remove(a) # dbl check if any from usemasked or useforced are still there masked = usemasked + useforced for a in use[:]: if a in masked: use.remove(a) return use
[ "def", "filter_flags", "(", "use", ",", "use_expand_hidden", ",", "usemasked", ",", "useforced", ")", ":", "portage", "=", "_get_portage", "(", ")", "# clean out some environment flags, since they will most probably", "# be confusing for the user", "for", "f", "in", "use_...
.. versionadded:: 2015.8.0 Filter function to remove hidden or otherwise not normally visible USE flags from a list. @type use: list @param use: the USE flag list to be filtered. @type use_expand_hidden: list @param use_expand_hidden: list of flags hidden. @type usemasked: list @param usemasked: list of masked USE flags. @type useforced: list @param useforced: the forced USE flags. @rtype: list @return the filtered USE flags.
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L640-L676
train
saltstack/salt
salt/modules/portage_config.py
get_all_cpv_use
def get_all_cpv_use(cp): ''' .. versionadded:: 2015.8.0 Uses portage to determine final USE flags and settings for an emerge. @type cp: string @param cp: eg cat/pkg @rtype: lists @return use, use_expand_hidden, usemask, useforce ''' cpv = _get_cpv(cp) portage = _get_portage() use = None _porttree().dbapi.settings.unlock() try: _porttree().dbapi.settings.setcpv(cpv, mydb=portage.portdb) use = portage.settings['PORTAGE_USE'].split() use_expand_hidden = portage.settings["USE_EXPAND_HIDDEN"].split() usemask = list(_porttree().dbapi.settings.usemask) useforce = list(_porttree().dbapi.settings.useforce) except KeyError: _porttree().dbapi.settings.reset() _porttree().dbapi.settings.lock() return [], [], [], [] # reset cpv filter _porttree().dbapi.settings.reset() _porttree().dbapi.settings.lock() return use, use_expand_hidden, usemask, useforce
python
def get_all_cpv_use(cp): ''' .. versionadded:: 2015.8.0 Uses portage to determine final USE flags and settings for an emerge. @type cp: string @param cp: eg cat/pkg @rtype: lists @return use, use_expand_hidden, usemask, useforce ''' cpv = _get_cpv(cp) portage = _get_portage() use = None _porttree().dbapi.settings.unlock() try: _porttree().dbapi.settings.setcpv(cpv, mydb=portage.portdb) use = portage.settings['PORTAGE_USE'].split() use_expand_hidden = portage.settings["USE_EXPAND_HIDDEN"].split() usemask = list(_porttree().dbapi.settings.usemask) useforce = list(_porttree().dbapi.settings.useforce) except KeyError: _porttree().dbapi.settings.reset() _porttree().dbapi.settings.lock() return [], [], [], [] # reset cpv filter _porttree().dbapi.settings.reset() _porttree().dbapi.settings.lock() return use, use_expand_hidden, usemask, useforce
[ "def", "get_all_cpv_use", "(", "cp", ")", ":", "cpv", "=", "_get_cpv", "(", "cp", ")", "portage", "=", "_get_portage", "(", ")", "use", "=", "None", "_porttree", "(", ")", ".", "dbapi", ".", "settings", ".", "unlock", "(", ")", "try", ":", "_porttree...
.. versionadded:: 2015.8.0 Uses portage to determine final USE flags and settings for an emerge. @type cp: string @param cp: eg cat/pkg @rtype: lists @return use, use_expand_hidden, usemask, useforce
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L679-L707
train
saltstack/salt
salt/modules/portage_config.py
get_cleared_flags
def get_cleared_flags(cp): ''' .. versionadded:: 2015.8.0 Uses portage for compare use flags which is used for installing package and use flags which now exist int /etc/portage/package.use/ @type cp: string @param cp: eg cat/pkg @rtype: tuple @rparam: tuple with two lists - list of used flags and list of flags which will be used ''' cpv = _get_cpv(cp) final_use, use_expand_hidden, usemasked, useforced = get_all_cpv_use(cpv) inst_flags = filter_flags(get_installed_use(cpv), use_expand_hidden, usemasked, useforced) final_flags = filter_flags(final_use, use_expand_hidden, usemasked, useforced) return inst_flags, final_flags
python
def get_cleared_flags(cp): ''' .. versionadded:: 2015.8.0 Uses portage for compare use flags which is used for installing package and use flags which now exist int /etc/portage/package.use/ @type cp: string @param cp: eg cat/pkg @rtype: tuple @rparam: tuple with two lists - list of used flags and list of flags which will be used ''' cpv = _get_cpv(cp) final_use, use_expand_hidden, usemasked, useforced = get_all_cpv_use(cpv) inst_flags = filter_flags(get_installed_use(cpv), use_expand_hidden, usemasked, useforced) final_flags = filter_flags(final_use, use_expand_hidden, usemasked, useforced) return inst_flags, final_flags
[ "def", "get_cleared_flags", "(", "cp", ")", ":", "cpv", "=", "_get_cpv", "(", "cp", ")", "final_use", ",", "use_expand_hidden", ",", "usemasked", ",", "useforced", "=", "get_all_cpv_use", "(", "cpv", ")", "inst_flags", "=", "filter_flags", "(", "get_installed_...
.. versionadded:: 2015.8.0 Uses portage for compare use flags which is used for installing package and use flags which now exist int /etc/portage/package.use/ @type cp: string @param cp: eg cat/pkg @rtype: tuple @rparam: tuple with two lists - list of used flags and list of flags which will be used
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L710-L729
train
saltstack/salt
salt/modules/portage_config.py
is_changed_uses
def is_changed_uses(cp): ''' .. versionadded:: 2015.8.0 Uses portage for determine if the use flags of installed package is compatible with use flags in portage configs. @type cp: string @param cp: eg cat/pkg ''' cpv = _get_cpv(cp) i_flags, conf_flags = get_cleared_flags(cpv) for i in i_flags: try: conf_flags.remove(i) except ValueError: return True return True if conf_flags else False
python
def is_changed_uses(cp): ''' .. versionadded:: 2015.8.0 Uses portage for determine if the use flags of installed package is compatible with use flags in portage configs. @type cp: string @param cp: eg cat/pkg ''' cpv = _get_cpv(cp) i_flags, conf_flags = get_cleared_flags(cpv) for i in i_flags: try: conf_flags.remove(i) except ValueError: return True return True if conf_flags else False
[ "def", "is_changed_uses", "(", "cp", ")", ":", "cpv", "=", "_get_cpv", "(", "cp", ")", "i_flags", ",", "conf_flags", "=", "get_cleared_flags", "(", "cpv", ")", "for", "i", "in", "i_flags", ":", "try", ":", "conf_flags", ".", "remove", "(", "i", ")", ...
.. versionadded:: 2015.8.0 Uses portage for determine if the use flags of installed package is compatible with use flags in portage configs. @type cp: string @param cp: eg cat/pkg
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L732-L749
train
saltstack/salt
salt/modules/cryptdev.py
active
def active(): ''' List existing device-mapper device details. ''' ret = {} # TODO: This command should be extended to collect more information, such as UUID. devices = __salt__['cmd.run_stdout']('dmsetup ls --target crypt') out_regex = re.compile(r'(?P<devname>\w+)\W+\((?P<major>\d+), (?P<minor>\d+)\)') log.debug(devices) for line in devices.split('\n'): match = out_regex.match(line) if match: dev_info = match.groupdict() ret[dev_info['devname']] = dev_info else: log.warning('dmsetup output does not match expected format') return ret
python
def active(): ''' List existing device-mapper device details. ''' ret = {} # TODO: This command should be extended to collect more information, such as UUID. devices = __salt__['cmd.run_stdout']('dmsetup ls --target crypt') out_regex = re.compile(r'(?P<devname>\w+)\W+\((?P<major>\d+), (?P<minor>\d+)\)') log.debug(devices) for line in devices.split('\n'): match = out_regex.match(line) if match: dev_info = match.groupdict() ret[dev_info['devname']] = dev_info else: log.warning('dmsetup output does not match expected format') return ret
[ "def", "active", "(", ")", ":", "ret", "=", "{", "}", "# TODO: This command should be extended to collect more information, such as UUID.", "devices", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "'dmsetup ls --target crypt'", ")", "out_regex", "=", "re", ".", "c...
List existing device-mapper device details.
[ "List", "existing", "device", "-", "mapper", "device", "details", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cryptdev.py#L111-L129
train
saltstack/salt
salt/modules/cryptdev.py
crypttab
def crypttab(config='/etc/crypttab'): ''' List the contents of the crypttab CLI Example: .. code-block:: bash salt '*' cryptdev.crypttab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line).rstrip('\n') try: entry = _crypttab_entry.dict_from_line(line) entry['options'] = entry['options'].split(',') # Handle duplicate names by appending `_` while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _crypttab_entry.ParseError: pass return ret
python
def crypttab(config='/etc/crypttab'): ''' List the contents of the crypttab CLI Example: .. code-block:: bash salt '*' cryptdev.crypttab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line).rstrip('\n') try: entry = _crypttab_entry.dict_from_line(line) entry['options'] = entry['options'].split(',') # Handle duplicate names by appending `_` while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _crypttab_entry.ParseError: pass return ret
[ "def", "crypttab", "(", "config", "=", "'/etc/crypttab'", ")", ":", "ret", "=", "{", "}", "if", "not", "os", ".", "path", ".", "isfile", "(", "config", ")", ":", "return", "ret", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "confi...
List the contents of the crypttab CLI Example: .. code-block:: bash salt '*' cryptdev.crypttab
[ "List", "the", "contents", "of", "the", "crypttab" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cryptdev.py#L132-L161
train
saltstack/salt
salt/modules/cryptdev.py
rm_crypttab
def rm_crypttab(name, config='/etc/crypttab'): ''' Remove the named mapping from the crypttab. If the described entry does not exist, nothing is changed, but the command succeeds by returning ``'absent'``. If a line is removed, it returns ``'change'``. CLI Example: .. code-block:: bash salt '*' cryptdev.rm_crypttab foo ''' modified = False criteria = _crypttab_entry(name=name) # For each line in the config that does not match the criteria, add it to # the list. At the end, re-create the config from just those lines. lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _crypttab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Could not read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'w+') as ofile: ofile.writelines((salt.utils.stringutils.to_str(line) for line in lines)) except (IOError, OSError) as exc: msg = 'Could not write to {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # If we reach this point, the changes were successful return 'change' if modified else 'absent'
python
def rm_crypttab(name, config='/etc/crypttab'): ''' Remove the named mapping from the crypttab. If the described entry does not exist, nothing is changed, but the command succeeds by returning ``'absent'``. If a line is removed, it returns ``'change'``. CLI Example: .. code-block:: bash salt '*' cryptdev.rm_crypttab foo ''' modified = False criteria = _crypttab_entry(name=name) # For each line in the config that does not match the criteria, add it to # the list. At the end, re-create the config from just those lines. lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _crypttab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Could not read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'w+') as ofile: ofile.writelines((salt.utils.stringutils.to_str(line) for line in lines)) except (IOError, OSError) as exc: msg = 'Could not write to {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # If we reach this point, the changes were successful return 'change' if modified else 'absent'
[ "def", "rm_crypttab", "(", "name", ",", "config", "=", "'/etc/crypttab'", ")", ":", "modified", "=", "False", "criteria", "=", "_crypttab_entry", "(", "name", "=", "name", ")", "# For each line in the config that does not match the criteria, add it to", "# the list. At th...
Remove the named mapping from the crypttab. If the described entry does not exist, nothing is changed, but the command succeeds by returning ``'absent'``. If a line is removed, it returns ``'change'``. CLI Example: .. code-block:: bash salt '*' cryptdev.rm_crypttab foo
[ "Remove", "the", "named", "mapping", "from", "the", "crypttab", ".", "If", "the", "described", "entry", "does", "not", "exist", "nothing", "is", "changed", "but", "the", "command", "succeeds", "by", "returning", "absent", ".", "If", "a", "line", "is", "rem...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cryptdev.py#L164-L208
train
saltstack/salt
salt/modules/cryptdev.py
set_crypttab
def set_crypttab( name, device, password='none', options='', config='/etc/crypttab', test=False, match_on='name'): ''' Verify that this device is represented in the crypttab, change the device to match the name passed, or add the name if it is not present. CLI Example: .. code-block:: bash salt '*' cryptdev.set_crypttab foo /dev/sdz1 mypassword swap,size=256 ''' # Fix the options type if it is not a string if options is None: options = '' elif isinstance(options, six.string_types): pass elif isinstance(options, list): options = ','.join(options) else: msg = 'options must be a string or list of strings' raise CommandExecutionError(msg) # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'password': password if password is not None else 'none', 'options': options, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _crypttab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _crypttab_entry.crypttab_keys invalid_keys = six.moves.filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _crypttab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not test: try: with salt.utils.files.fopen(config, 'w+') as ofile: # The line was changed, commit it! ofile.writelines((salt.utils.stringutils.to_str(line) for line in lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret
python
def set_crypttab( name, device, password='none', options='', config='/etc/crypttab', test=False, match_on='name'): ''' Verify that this device is represented in the crypttab, change the device to match the name passed, or add the name if it is not present. CLI Example: .. code-block:: bash salt '*' cryptdev.set_crypttab foo /dev/sdz1 mypassword swap,size=256 ''' # Fix the options type if it is not a string if options is None: options = '' elif isinstance(options, six.string_types): pass elif isinstance(options, list): options = ','.join(options) else: msg = 'options must be a string or list of strings' raise CommandExecutionError(msg) # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'password': password if password is not None else 'none', 'options': options, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _crypttab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _crypttab_entry.crypttab_keys invalid_keys = six.moves.filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _crypttab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not test: try: with salt.utils.files.fopen(config, 'w+') as ofile: # The line was changed, commit it! ofile.writelines((salt.utils.stringutils.to_str(line) for line in lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret
[ "def", "set_crypttab", "(", "name", ",", "device", ",", "password", "=", "'none'", ",", "options", "=", "''", ",", "config", "=", "'/etc/crypttab'", ",", "test", "=", "False", ",", "match_on", "=", "'name'", ")", ":", "# Fix the options type if it is not a str...
Verify that this device is represented in the crypttab, change the device to match the name passed, or add the name if it is not present. CLI Example: .. code-block:: bash salt '*' cryptdev.set_crypttab foo /dev/sdz1 mypassword swap,size=256
[ "Verify", "that", "this", "device", "is", "represented", "in", "the", "crypttab", "change", "the", "device", "to", "match", "the", "name", "passed", "or", "add", "the", "name", "if", "it", "is", "not", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cryptdev.py#L211-L316
train
saltstack/salt
salt/modules/cryptdev.py
open
def open(name, device, keyfile): ''' Open a crypt device using ``cryptsetup``. The ``keyfile`` must not be ``None`` or ``'none'``, because ``cryptsetup`` will otherwise ask for the password interactively. CLI Example: .. code-block:: bash salt '*' cryptdev.open foo /dev/sdz1 /path/to/keyfile ''' if keyfile is None or keyfile == 'none' or keyfile == '-': raise CommandExecutionError('For immediate crypt device mapping, keyfile must not be none') code = __salt__['cmd.retcode']('cryptsetup open --key-file {0} {1} {2}' .format(keyfile, device, name)) return code == 0
python
def open(name, device, keyfile): ''' Open a crypt device using ``cryptsetup``. The ``keyfile`` must not be ``None`` or ``'none'``, because ``cryptsetup`` will otherwise ask for the password interactively. CLI Example: .. code-block:: bash salt '*' cryptdev.open foo /dev/sdz1 /path/to/keyfile ''' if keyfile is None or keyfile == 'none' or keyfile == '-': raise CommandExecutionError('For immediate crypt device mapping, keyfile must not be none') code = __salt__['cmd.retcode']('cryptsetup open --key-file {0} {1} {2}' .format(keyfile, device, name)) return code == 0
[ "def", "open", "(", "name", ",", "device", ",", "keyfile", ")", ":", "if", "keyfile", "is", "None", "or", "keyfile", "==", "'none'", "or", "keyfile", "==", "'-'", ":", "raise", "CommandExecutionError", "(", "'For immediate crypt device mapping, keyfile must not be...
Open a crypt device using ``cryptsetup``. The ``keyfile`` must not be ``None`` or ``'none'``, because ``cryptsetup`` will otherwise ask for the password interactively. CLI Example: .. code-block:: bash salt '*' cryptdev.open foo /dev/sdz1 /path/to/keyfile
[ "Open", "a", "crypt", "device", "using", "cryptsetup", ".", "The", "keyfile", "must", "not", "be", "None", "or", "none", "because", "cryptsetup", "will", "otherwise", "ask", "for", "the", "password", "interactively", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cryptdev.py#L319-L336
train
saltstack/salt
salt/states/keystone_user.py
present
def present(name, auth=None, **kwargs): ''' Ensure domain exists and is up-to-date name Name of the domain domain The name or id of the domain enabled Boolean to control if domain is enabled description An arbitrary description of the domain password The user password email The users email address ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} kwargs = __utils__['args.clean_kwargs'](**kwargs) __salt__['keystoneng.setup_clouds'](auth) kwargs['name'] = name user = _common(kwargs) if user is None: if __opts__['test'] is True: ret['result'] = None ret['changes'] = kwargs ret['comment'] = 'User will be created.' return ret user = __salt__['keystoneng.user_create'](**kwargs) ret['changes'] = user ret['comment'] = 'Created user' return ret changes = __salt__['keystoneng.compare_changes'](user, **kwargs) if changes: if __opts__['test'] is True: ret['result'] = None ret['changes'] = changes ret['comment'] = 'User will be updated.' return ret kwargs['name'] = user __salt__['keystoneng.user_update'](**kwargs) ret['changes'].update(changes) ret['comment'] = 'Updated user' return ret
python
def present(name, auth=None, **kwargs): ''' Ensure domain exists and is up-to-date name Name of the domain domain The name or id of the domain enabled Boolean to control if domain is enabled description An arbitrary description of the domain password The user password email The users email address ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} kwargs = __utils__['args.clean_kwargs'](**kwargs) __salt__['keystoneng.setup_clouds'](auth) kwargs['name'] = name user = _common(kwargs) if user is None: if __opts__['test'] is True: ret['result'] = None ret['changes'] = kwargs ret['comment'] = 'User will be created.' return ret user = __salt__['keystoneng.user_create'](**kwargs) ret['changes'] = user ret['comment'] = 'Created user' return ret changes = __salt__['keystoneng.compare_changes'](user, **kwargs) if changes: if __opts__['test'] is True: ret['result'] = None ret['changes'] = changes ret['comment'] = 'User will be updated.' return ret kwargs['name'] = user __salt__['keystoneng.user_update'](**kwargs) ret['changes'].update(changes) ret['comment'] = 'Updated user' return ret
[ "def", "present", "(", "name", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "kwargs", "=", ...
Ensure domain exists and is up-to-date name Name of the domain domain The name or id of the domain enabled Boolean to control if domain is enabled description An arbitrary description of the domain password The user password email The users email address
[ "Ensure", "domain", "exists", "and", "is", "up", "-", "to", "-", "date" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_user.py#L59-L118
train
saltstack/salt
salt/states/lvs_server.py
present
def present(name, protocol=None, service_address=None, server_address=None, packet_forward_method='dr', weight=1 ): ''' Ensure that the named service is present. name The LVS server name protocol The service protocol service_address The LVS service address server_address The real server address. packet_forward_method The LVS packet forwarding method(``dr`` for direct routing, ``tunnel`` for tunneling, ``nat`` for network access translation). weight The capacity of a server relative to the others in the pool. .. code-block:: yaml lvsrs: lvs_server.present: - protocol: tcp - service_address: 1.1.1.1:80 - server_address: 192.168.0.11:8080 - packet_forward_method: dr - weight: 10 ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check server server_check = __salt__['lvs.check_server'](protocol=protocol, service_address=service_address, server_address=server_address) if server_check is True: server_rule_check = __salt__['lvs.check_server'](protocol=protocol, service_address=service_address, server_address=server_address, packet_forward_method=packet_forward_method, weight=weight) if server_rule_check is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) is present'.format(name, service_address, protocol) return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Server {0} in service {1}({2}) is present but some options should update'.format(name, service_address, protocol) return ret else: server_edit = __salt__['lvs.edit_server'](protocol=protocol, service_address=service_address, server_address=server_address, packet_forward_method=packet_forward_method, weight=weight) if server_edit is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) has been updated'.format(name, service_address, protocol) ret['changes'][name] = 'Update' return ret else: ret['result'] = False ret['comment'] = 'LVS Server {0} in service {1}({2}) update failed({3})'.format(name, service_address, protocol, server_edit) return ret else: if __opts__['test']: ret['comment'] = 'LVS Server {0} in service {1}({2}) is not present and needs to be created'.format(name, service_address, protocol) ret['result'] = None return ret else: server_add = __salt__['lvs.add_server'](protocol=protocol, service_address=service_address, server_address=server_address, packet_forward_method=packet_forward_method, weight=weight) if server_add is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) has been created'.format(name, service_address, protocol) ret['changes'][name] = 'Present' return ret else: ret['comment'] = 'LVS Service {0} in service {1}({2}) create failed({3})'.format(name, service_address, protocol, server_add) ret['result'] = False return ret
python
def present(name, protocol=None, service_address=None, server_address=None, packet_forward_method='dr', weight=1 ): ''' Ensure that the named service is present. name The LVS server name protocol The service protocol service_address The LVS service address server_address The real server address. packet_forward_method The LVS packet forwarding method(``dr`` for direct routing, ``tunnel`` for tunneling, ``nat`` for network access translation). weight The capacity of a server relative to the others in the pool. .. code-block:: yaml lvsrs: lvs_server.present: - protocol: tcp - service_address: 1.1.1.1:80 - server_address: 192.168.0.11:8080 - packet_forward_method: dr - weight: 10 ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check server server_check = __salt__['lvs.check_server'](protocol=protocol, service_address=service_address, server_address=server_address) if server_check is True: server_rule_check = __salt__['lvs.check_server'](protocol=protocol, service_address=service_address, server_address=server_address, packet_forward_method=packet_forward_method, weight=weight) if server_rule_check is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) is present'.format(name, service_address, protocol) return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Server {0} in service {1}({2}) is present but some options should update'.format(name, service_address, protocol) return ret else: server_edit = __salt__['lvs.edit_server'](protocol=protocol, service_address=service_address, server_address=server_address, packet_forward_method=packet_forward_method, weight=weight) if server_edit is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) has been updated'.format(name, service_address, protocol) ret['changes'][name] = 'Update' return ret else: ret['result'] = False ret['comment'] = 'LVS Server {0} in service {1}({2}) update failed({3})'.format(name, service_address, protocol, server_edit) return ret else: if __opts__['test']: ret['comment'] = 'LVS Server {0} in service {1}({2}) is not present and needs to be created'.format(name, service_address, protocol) ret['result'] = None return ret else: server_add = __salt__['lvs.add_server'](protocol=protocol, service_address=service_address, server_address=server_address, packet_forward_method=packet_forward_method, weight=weight) if server_add is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) has been created'.format(name, service_address, protocol) ret['changes'][name] = 'Present' return ret else: ret['comment'] = 'LVS Service {0} in service {1}({2}) create failed({3})'.format(name, service_address, protocol, server_add) ret['result'] = False return ret
[ "def", "present", "(", "name", ",", "protocol", "=", "None", ",", "service_address", "=", "None", ",", "server_address", "=", "None", ",", "packet_forward_method", "=", "'dr'", ",", "weight", "=", "1", ")", ":", "ret", "=", "{", "'name'", ":", "name", ...
Ensure that the named service is present. name The LVS server name protocol The service protocol service_address The LVS service address server_address The real server address. packet_forward_method The LVS packet forwarding method(``dr`` for direct routing, ``tunnel`` for tunneling, ``nat`` for network access translation). weight The capacity of a server relative to the others in the pool. .. code-block:: yaml lvsrs: lvs_server.present: - protocol: tcp - service_address: 1.1.1.1:80 - server_address: 192.168.0.11:8080 - packet_forward_method: dr - weight: 10
[ "Ensure", "that", "the", "named", "service", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lvs_server.py#L18-L112
train
saltstack/salt
salt/states/lvs_server.py
absent
def absent(name, protocol=None, service_address=None, server_address=None): ''' Ensure the LVS Real Server in specified service is absent. name The name of the LVS server. protocol The service protocol(only support ``tcp``, ``udp`` and ``fwmark`` service). service_address The LVS service address. server_address The LVS real server address. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if server exists and remove it server_check = __salt__['lvs.check_server'](protocol=protocol, service_address=service_address, server_address=server_address) if server_check is True: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Server {0} in service {1}({2}) is present and needs to be removed'.format(name, service_address, protocol) return ret server_delete = __salt__['lvs.delete_server'](protocol=protocol, service_address=service_address, server_address=server_address) if server_delete is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) has been removed'.format(name, service_address, protocol) ret['changes'][name] = 'Absent' return ret else: ret['comment'] = 'LVS Server {0} in service {1}({2}) removed failed({3})'.format(name, service_address, protocol, server_delete) ret['result'] = False return ret else: ret['comment'] = 'LVS Server {0} in service {1}({2}) is not present, so it cannot be removed'.format(name, service_address, protocol) return ret
python
def absent(name, protocol=None, service_address=None, server_address=None): ''' Ensure the LVS Real Server in specified service is absent. name The name of the LVS server. protocol The service protocol(only support ``tcp``, ``udp`` and ``fwmark`` service). service_address The LVS service address. server_address The LVS real server address. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if server exists and remove it server_check = __salt__['lvs.check_server'](protocol=protocol, service_address=service_address, server_address=server_address) if server_check is True: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Server {0} in service {1}({2}) is present and needs to be removed'.format(name, service_address, protocol) return ret server_delete = __salt__['lvs.delete_server'](protocol=protocol, service_address=service_address, server_address=server_address) if server_delete is True: ret['comment'] = 'LVS Server {0} in service {1}({2}) has been removed'.format(name, service_address, protocol) ret['changes'][name] = 'Absent' return ret else: ret['comment'] = 'LVS Server {0} in service {1}({2}) removed failed({3})'.format(name, service_address, protocol, server_delete) ret['result'] = False return ret else: ret['comment'] = 'LVS Server {0} in service {1}({2}) is not present, so it cannot be removed'.format(name, service_address, protocol) return ret
[ "def", "absent", "(", "name", ",", "protocol", "=", "None", ",", "service_address", "=", "None", ",", "server_address", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",",...
Ensure the LVS Real Server in specified service is absent. name The name of the LVS server. protocol The service protocol(only support ``tcp``, ``udp`` and ``fwmark`` service). service_address The LVS service address. server_address The LVS real server address.
[ "Ensure", "the", "LVS", "Real", "Server", "in", "specified", "service", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lvs_server.py#L115-L159
train
saltstack/salt
salt/states/influxdb08_user.py
present
def present(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Ensure that the cluster admin or database user is present. name The name of the user to manage passwd The password of the user database The database to create the user in user The user to connect as (must be able to create the user) password The password of the user host The host to connect to port The port to connect to ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} # check if db does not exist if database and not __salt__['influxdb08.db_exists']( database, user, password, host, port): ret['result'] = False ret['comment'] = 'Database {0} does not exist'.format(database) return ret # check if user exists if not __salt__['influxdb08.user_exists']( name, database, user, password, host, port): if __opts__['test']: ret['result'] = None ret['comment'] = 'User {0} is not present and needs to be created'\ .format(name) return ret # The user is not present, make it! if __salt__['influxdb08.user_create']( name, passwd, database, user, password, host, port): ret['comment'] = 'User {0} has been created'.format(name) ret['changes'][name] = 'Present' return ret else: ret['comment'] = 'Failed to create user {0}'.format(name) ret['result'] = False return ret # fallback ret['comment'] = 'User {0} is already present'.format(name) return ret
python
def present(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Ensure that the cluster admin or database user is present. name The name of the user to manage passwd The password of the user database The database to create the user in user The user to connect as (must be able to create the user) password The password of the user host The host to connect to port The port to connect to ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} # check if db does not exist if database and not __salt__['influxdb08.db_exists']( database, user, password, host, port): ret['result'] = False ret['comment'] = 'Database {0} does not exist'.format(database) return ret # check if user exists if not __salt__['influxdb08.user_exists']( name, database, user, password, host, port): if __opts__['test']: ret['result'] = None ret['comment'] = 'User {0} is not present and needs to be created'\ .format(name) return ret # The user is not present, make it! if __salt__['influxdb08.user_create']( name, passwd, database, user, password, host, port): ret['comment'] = 'User {0} has been created'.format(name) ret['changes'][name] = 'Present' return ret else: ret['comment'] = 'Failed to create user {0}'.format(name) ret['result'] = False return ret # fallback ret['comment'] = 'User {0} is already present'.format(name) return ret
[ "def", "present", "(", "name", ",", "passwd", ",", "database", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'chang...
Ensure that the cluster admin or database user is present. name The name of the user to manage passwd The password of the user database The database to create the user in user The user to connect as (must be able to create the user) password The password of the user host The host to connect to port The port to connect to
[ "Ensure", "that", "the", "cluster", "admin", "or", "database", "user", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/influxdb08_user.py#L25-L90
train
saltstack/salt
salt/modules/openbsdpkg.py
list_pkgs
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret ret = {} cmd = 'pkg_info -q -a' out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace') for line in out.splitlines(): try: pkgname, pkgver, flavor = __PKG_RE.match(line).groups() except AttributeError: continue pkgname += '--{0}'.format(flavor) if flavor else '' __salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret
python
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret ret = {} cmd = 'pkg_info -q -a' out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace') for line in out.splitlines(): try: pkgname, pkgver, flavor = __PKG_RE.match(line).groups() except AttributeError: continue pkgname += '--{0}'.format(flavor) if flavor else '' __salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret
[ "def", "list_pkgs", "(", "versions_as_list", "=", "False", ",", "*", "*", "kwargs", ")", ":", "versions_as_list", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "versions_as_list", ")", "# not yet implemented or not applicable", "if", "any", "(", ...
List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
[ "List", "the", "packages", "currently", "installed", "as", "a", "dict", "::" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L57-L98
train
saltstack/salt
salt/modules/openbsdpkg.py
install
def install(name=None, pkgs=None, sources=None, **kwargs): ''' Install the passed package Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example, Install one package: .. code-block:: bash salt '*' pkg.install <package name> CLI Example, Install more than one package: .. code-block:: bash salt '*' pkg.install pkgs='["<package name>", "<package name>"]' CLI Example, Install more than one package from a alternate source (e.g. salt file-server, HTTP, FTP, local filesystem): .. code-block:: bash salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' ''' try: pkg_params, pkg_type = __salt__['pkg_resource.parse_targets']( name, pkgs, sources, **kwargs ) except MinionError as exc: raise CommandExecutionError(exc) if not pkg_params: return {} old = list_pkgs() errors = [] for pkg in pkg_params: # A special case for OpenBSD package "branches" is also required in # salt/states/pkg.py if pkg_type == 'repository': stem, branch = (pkg.split('%') + [''])[:2] base, flavor = (stem.split('--') + [''])[:2] pkg = '{0}--{1}%{2}'.format(base, flavor, branch) cmd = 'pkg_add -x -I {0}'.format(pkg) out = __salt__['cmd.run_all']( cmd, python_shell=False, output_loglevel='trace' ) if out['retcode'] != 0 and out['stderr']: errors.append(out['stderr']) __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret
python
def install(name=None, pkgs=None, sources=None, **kwargs): ''' Install the passed package Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example, Install one package: .. code-block:: bash salt '*' pkg.install <package name> CLI Example, Install more than one package: .. code-block:: bash salt '*' pkg.install pkgs='["<package name>", "<package name>"]' CLI Example, Install more than one package from a alternate source (e.g. salt file-server, HTTP, FTP, local filesystem): .. code-block:: bash salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' ''' try: pkg_params, pkg_type = __salt__['pkg_resource.parse_targets']( name, pkgs, sources, **kwargs ) except MinionError as exc: raise CommandExecutionError(exc) if not pkg_params: return {} old = list_pkgs() errors = [] for pkg in pkg_params: # A special case for OpenBSD package "branches" is also required in # salt/states/pkg.py if pkg_type == 'repository': stem, branch = (pkg.split('%') + [''])[:2] base, flavor = (stem.split('--') + [''])[:2] pkg = '{0}--{1}%{2}'.format(base, flavor, branch) cmd = 'pkg_add -x -I {0}'.format(pkg) out = __salt__['cmd.run_all']( cmd, python_shell=False, output_loglevel='trace' ) if out['retcode'] != 0 and out['stderr']: errors.append(out['stderr']) __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret
[ "def", "install", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "pkg_params", ",", "pkg_type", "=", "__salt__", "[", "'pkg_resource.parse_targets'", "]", "(", "name", ","...
Install the passed package Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example, Install one package: .. code-block:: bash salt '*' pkg.install <package name> CLI Example, Install more than one package: .. code-block:: bash salt '*' pkg.install pkgs='["<package name>", "<package name>"]' CLI Example, Install more than one package from a alternate source (e.g. salt file-server, HTTP, FTP, local filesystem): .. code-block:: bash salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]'
[ "Install", "the", "passed", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L184-L250
train
saltstack/salt
salt/modules/openbsdpkg.py
remove
def remove(name=None, pkgs=None, purge=False, **kwargs): ''' Remove a single package with pkg_delete Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' try: pkg_params = [x.split('--')[0] for x in __salt__['pkg_resource.parse_targets'](name, pkgs)[0]] except MinionError as exc: raise CommandExecutionError(exc) old = list_pkgs() targets = [x for x in pkg_params if x in old] if not targets: return {} cmd = ['pkg_delete', '-Ix', '-Ddependencies'] if purge: cmd.append('-cqq') cmd.extend(targets) out = __salt__['cmd.run_all']( cmd, python_shell=False, output_loglevel='trace' ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret
python
def remove(name=None, pkgs=None, purge=False, **kwargs): ''' Remove a single package with pkg_delete Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' try: pkg_params = [x.split('--')[0] for x in __salt__['pkg_resource.parse_targets'](name, pkgs)[0]] except MinionError as exc: raise CommandExecutionError(exc) old = list_pkgs() targets = [x for x in pkg_params if x in old] if not targets: return {} cmd = ['pkg_delete', '-Ix', '-Ddependencies'] if purge: cmd.append('-cqq') cmd.extend(targets) out = __salt__['cmd.run_all']( cmd, python_shell=False, output_loglevel='trace' ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret
[ "def", "remove", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "purge", "=", "False", ",", "*", "*", "kwargs", ")", ":", "try", ":", "pkg_params", "=", "[", "x", ".", "split", "(", "'--'", ")", "[", "0", "]", "for", "x", "in", "__s...
Remove a single package with pkg_delete Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]'
[ "Remove", "a", "single", "package", "with", "pkg_delete" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L253-L314
train
saltstack/salt
salt/modules/openbsdpkg.py
purge
def purge(name=None, pkgs=None, **kwargs): ''' Remove a package and extra configuration files. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.purge <package name> salt '*' pkg.purge <package1>,<package2>,<package3> salt '*' pkg.purge pkgs='["foo", "bar"]' ''' return remove(name=name, pkgs=pkgs, purge=True)
python
def purge(name=None, pkgs=None, **kwargs): ''' Remove a package and extra configuration files. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.purge <package name> salt '*' pkg.purge <package1>,<package2>,<package3> salt '*' pkg.purge pkgs='["foo", "bar"]' ''' return remove(name=name, pkgs=pkgs, purge=True)
[ "def", "purge", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "remove", "(", "name", "=", "name", ",", "pkgs", "=", "pkgs", ",", "purge", "=", "True", ")" ]
Remove a package and extra configuration files. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.purge <package name> salt '*' pkg.purge <package1>,<package2>,<package3> salt '*' pkg.purge pkgs='["foo", "bar"]'
[ "Remove", "a", "package", "and", "extra", "configuration", "files", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L317-L344
train
saltstack/salt
salt/modules/openbsdpkg.py
upgrade
def upgrade(name=None, pkgs=None, **kwargs): ''' Run a full package upgrade (``pkg_add -u``), or upgrade a specific package if ``name`` or ``pkgs`` is provided. ``name`` is ignored when ``pkgs`` is specified. Returns a dictionary containing the changes: .. versionadded:: 2019.2.0 .. code-block:: python {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade salt '*' pkg.upgrade python%2.7 ''' old = list_pkgs() cmd = ['pkg_add', '-Ix', '-u'] if kwargs.get('noop', False): cmd.append('-n') if pkgs: cmd.extend(pkgs) elif name: cmd.append(name) # Now run the upgrade, compare the list of installed packages before and # after and we have all the info we need. result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered upgrading packages', info={'changes': ret, 'result': result} ) return ret
python
def upgrade(name=None, pkgs=None, **kwargs): ''' Run a full package upgrade (``pkg_add -u``), or upgrade a specific package if ``name`` or ``pkgs`` is provided. ``name`` is ignored when ``pkgs`` is specified. Returns a dictionary containing the changes: .. versionadded:: 2019.2.0 .. code-block:: python {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade salt '*' pkg.upgrade python%2.7 ''' old = list_pkgs() cmd = ['pkg_add', '-Ix', '-u'] if kwargs.get('noop', False): cmd.append('-n') if pkgs: cmd.extend(pkgs) elif name: cmd.append(name) # Now run the upgrade, compare the list of installed packages before and # after and we have all the info we need. result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered upgrading packages', info={'changes': ret, 'result': result} ) return ret
[ "def", "upgrade", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "old", "=", "list_pkgs", "(", ")", "cmd", "=", "[", "'pkg_add'", ",", "'-Ix'", ",", "'-u'", "]", "if", "kwargs", ".", "get", "(", "'noop'", ...
Run a full package upgrade (``pkg_add -u``), or upgrade a specific package if ``name`` or ``pkgs`` is provided. ``name`` is ignored when ``pkgs`` is specified. Returns a dictionary containing the changes: .. versionadded:: 2019.2.0 .. code-block:: python {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade salt '*' pkg.upgrade python%2.7
[ "Run", "a", "full", "package", "upgrade", "(", "pkg_add", "-", "u", ")", "or", "upgrade", "a", "specific", "package", "if", "name", "or", "pkgs", "is", "provided", ".", "name", "is", "ignored", "when", "pkgs", "is", "specified", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L362-L413
train
saltstack/salt
salt/states/boto_datapipeline.py
present
def present(name, pipeline_objects=None, pipeline_objects_from_pillars='boto_datapipeline_pipeline_objects', parameter_objects=None, parameter_objects_from_pillars='boto_datapipeline_parameter_objects', parameter_values=None, parameter_values_from_pillars='boto_datapipeline_parameter_values', region=None, key=None, keyid=None, profile=None): ''' Ensure the data pipeline exists with matching definition. name Name of the service to ensure a data pipeline exists for. pipeline_objects Pipeline objects to use. Will override objects read from pillars. pipeline_objects_from_pillars The pillar key to use for lookup. parameter_objects Parameter objects to use. Will override objects read from pillars. parameter_objects_from_pillars The pillar key to use for lookup. parameter_values Parameter values to use. Will override values read from pillars. parameter_values_from_pillars The pillar key to use for lookup. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} pipeline_objects = pipeline_objects or {} parameter_objects = parameter_objects or {} parameter_values = parameter_values or {} present, old_pipeline_definition = _pipeline_present_with_definition( name, _pipeline_objects(pipeline_objects_from_pillars, pipeline_objects), _parameter_objects(parameter_objects_from_pillars, parameter_objects), _parameter_values(parameter_values_from_pillars, parameter_values), region=region, key=key, keyid=keyid, profile=profile, ) if present: ret['comment'] = 'AWS data pipeline {0} present'.format(name) return ret if __opts__['test']: ret['comment'] = 'Data pipeline {0} is set to be created or updated'.format(name) ret['result'] = None return ret result_create_pipeline = __salt__['boto_datapipeline.create_pipeline']( name, name, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_create_pipeline: ret['result'] = False ret['comment'] = 'Failed to create data pipeline {0}: {1}'.format( name, result_create_pipeline['error']) return ret pipeline_id = result_create_pipeline['result'] result_pipeline_definition = __salt__['boto_datapipeline.put_pipeline_definition']( pipeline_id, _pipeline_objects(pipeline_objects_from_pillars, pipeline_objects), parameter_objects=_parameter_objects(parameter_objects_from_pillars, parameter_objects), parameter_values=_parameter_values(parameter_values_from_pillars, parameter_values), region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_pipeline_definition: if _immutable_fields_error(result_pipeline_definition): # If update not possible, delete and retry result_delete_pipeline = __salt__['boto_datapipeline.delete_pipeline']( pipeline_id, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_delete_pipeline: ret['result'] = False ret['comment'] = 'Failed to delete data pipeline {0}: {1}'.format( pipeline_id, result_delete_pipeline['error']) return ret result_create_pipeline = __salt__['boto_datapipeline.create_pipeline']( name, name, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_create_pipeline: ret['result'] = False ret['comment'] = 'Failed to create data pipeline {0}: {1}'.format( name, result_create_pipeline['error']) return ret pipeline_id = result_create_pipeline['result'] result_pipeline_definition = __salt__['boto_datapipeline.put_pipeline_definition']( pipeline_id, _pipeline_objects(pipeline_objects_from_pillars, pipeline_objects), parameter_objects=_parameter_objects(parameter_objects_from_pillars, parameter_objects), parameter_values=_parameter_values(parameter_values_from_pillars, parameter_values), region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_pipeline_definition: # Still erroring after possible retry ret['result'] = False ret['comment'] = 'Failed to create data pipeline {0}: {1}'.format( name, result_pipeline_definition['error']) return ret result_activate_pipeline = __salt__['boto_datapipeline.activate_pipeline']( pipeline_id, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_activate_pipeline: ret['result'] = False ret['comment'] = 'Failed to create data pipeline {0}: {1}'.format( name, result_pipeline_definition['error']) return ret pipeline_definition_result = __salt__['boto_datapipeline.get_pipeline_definition']( pipeline_id, version='active', region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in pipeline_definition_result: new_pipeline_definition = {} else: new_pipeline_definition = _standardize(pipeline_definition_result['result']) if not old_pipeline_definition: ret['changes']['new'] = 'Pipeline created.' ret['comment'] = 'Data pipeline {0} created'.format(name) else: ret['changes']['diff'] = _diff(old_pipeline_definition, new_pipeline_definition) ret['comment'] = 'Data pipeline {0} updated'.format(name) return ret
python
def present(name, pipeline_objects=None, pipeline_objects_from_pillars='boto_datapipeline_pipeline_objects', parameter_objects=None, parameter_objects_from_pillars='boto_datapipeline_parameter_objects', parameter_values=None, parameter_values_from_pillars='boto_datapipeline_parameter_values', region=None, key=None, keyid=None, profile=None): ''' Ensure the data pipeline exists with matching definition. name Name of the service to ensure a data pipeline exists for. pipeline_objects Pipeline objects to use. Will override objects read from pillars. pipeline_objects_from_pillars The pillar key to use for lookup. parameter_objects Parameter objects to use. Will override objects read from pillars. parameter_objects_from_pillars The pillar key to use for lookup. parameter_values Parameter values to use. Will override values read from pillars. parameter_values_from_pillars The pillar key to use for lookup. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} pipeline_objects = pipeline_objects or {} parameter_objects = parameter_objects or {} parameter_values = parameter_values or {} present, old_pipeline_definition = _pipeline_present_with_definition( name, _pipeline_objects(pipeline_objects_from_pillars, pipeline_objects), _parameter_objects(parameter_objects_from_pillars, parameter_objects), _parameter_values(parameter_values_from_pillars, parameter_values), region=region, key=key, keyid=keyid, profile=profile, ) if present: ret['comment'] = 'AWS data pipeline {0} present'.format(name) return ret if __opts__['test']: ret['comment'] = 'Data pipeline {0} is set to be created or updated'.format(name) ret['result'] = None return ret result_create_pipeline = __salt__['boto_datapipeline.create_pipeline']( name, name, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_create_pipeline: ret['result'] = False ret['comment'] = 'Failed to create data pipeline {0}: {1}'.format( name, result_create_pipeline['error']) return ret pipeline_id = result_create_pipeline['result'] result_pipeline_definition = __salt__['boto_datapipeline.put_pipeline_definition']( pipeline_id, _pipeline_objects(pipeline_objects_from_pillars, pipeline_objects), parameter_objects=_parameter_objects(parameter_objects_from_pillars, parameter_objects), parameter_values=_parameter_values(parameter_values_from_pillars, parameter_values), region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_pipeline_definition: if _immutable_fields_error(result_pipeline_definition): # If update not possible, delete and retry result_delete_pipeline = __salt__['boto_datapipeline.delete_pipeline']( pipeline_id, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_delete_pipeline: ret['result'] = False ret['comment'] = 'Failed to delete data pipeline {0}: {1}'.format( pipeline_id, result_delete_pipeline['error']) return ret result_create_pipeline = __salt__['boto_datapipeline.create_pipeline']( name, name, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_create_pipeline: ret['result'] = False ret['comment'] = 'Failed to create data pipeline {0}: {1}'.format( name, result_create_pipeline['error']) return ret pipeline_id = result_create_pipeline['result'] result_pipeline_definition = __salt__['boto_datapipeline.put_pipeline_definition']( pipeline_id, _pipeline_objects(pipeline_objects_from_pillars, pipeline_objects), parameter_objects=_parameter_objects(parameter_objects_from_pillars, parameter_objects), parameter_values=_parameter_values(parameter_values_from_pillars, parameter_values), region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_pipeline_definition: # Still erroring after possible retry ret['result'] = False ret['comment'] = 'Failed to create data pipeline {0}: {1}'.format( name, result_pipeline_definition['error']) return ret result_activate_pipeline = __salt__['boto_datapipeline.activate_pipeline']( pipeline_id, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_activate_pipeline: ret['result'] = False ret['comment'] = 'Failed to create data pipeline {0}: {1}'.format( name, result_pipeline_definition['error']) return ret pipeline_definition_result = __salt__['boto_datapipeline.get_pipeline_definition']( pipeline_id, version='active', region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in pipeline_definition_result: new_pipeline_definition = {} else: new_pipeline_definition = _standardize(pipeline_definition_result['result']) if not old_pipeline_definition: ret['changes']['new'] = 'Pipeline created.' ret['comment'] = 'Data pipeline {0} created'.format(name) else: ret['changes']['diff'] = _diff(old_pipeline_definition, new_pipeline_definition) ret['comment'] = 'Data pipeline {0} updated'.format(name) return ret
[ "def", "present", "(", "name", ",", "pipeline_objects", "=", "None", ",", "pipeline_objects_from_pillars", "=", "'boto_datapipeline_pipeline_objects'", ",", "parameter_objects", "=", "None", ",", "parameter_objects_from_pillars", "=", "'boto_datapipeline_parameter_objects'", ...
Ensure the data pipeline exists with matching definition. name Name of the service to ensure a data pipeline exists for. pipeline_objects Pipeline objects to use. Will override objects read from pillars. pipeline_objects_from_pillars The pillar key to use for lookup. parameter_objects Parameter objects to use. Will override objects read from pillars. parameter_objects_from_pillars The pillar key to use for lookup. parameter_values Parameter values to use. Will override values read from pillars. parameter_values_from_pillars The pillar key to use for lookup. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Ensure", "the", "data", "pipeline", "exists", "with", "matching", "definition", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L72-L251
train
saltstack/salt
salt/states/boto_datapipeline.py
_pipeline_present_with_definition
def _pipeline_present_with_definition(name, expected_pipeline_objects, expected_parameter_objects, expected_parameter_values, region, key, keyid, profile): ''' Return true if the pipeline exists and the definition matches. name The name of the pipeline. expected_pipeline_objects Pipeline objects that must match the definition. expected_parameter_objects Parameter objects that must match the definition. expected_parameter_values Parameter values that must match the definition. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' result_pipeline_id = __salt__['boto_datapipeline.pipeline_id_from_name']( name, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_pipeline_id: return False, {} pipeline_id = result_pipeline_id['result'] pipeline_definition_result = __salt__['boto_datapipeline.get_pipeline_definition']( pipeline_id, version='active', region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in pipeline_definition_result: return False, {} pipeline_definition = _standardize(pipeline_definition_result['result']) pipeline_objects = pipeline_definition.get('pipelineObjects') parameter_objects = pipeline_definition.get('parameterObjects') parameter_values = pipeline_definition.get('parameterValues') present = (_recursive_compare(_cleaned(pipeline_objects), _cleaned(expected_pipeline_objects)) and _recursive_compare(parameter_objects, expected_parameter_objects) and _recursive_compare(parameter_values, expected_parameter_values)) return present, pipeline_definition
python
def _pipeline_present_with_definition(name, expected_pipeline_objects, expected_parameter_objects, expected_parameter_values, region, key, keyid, profile): ''' Return true if the pipeline exists and the definition matches. name The name of the pipeline. expected_pipeline_objects Pipeline objects that must match the definition. expected_parameter_objects Parameter objects that must match the definition. expected_parameter_values Parameter values that must match the definition. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' result_pipeline_id = __salt__['boto_datapipeline.pipeline_id_from_name']( name, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in result_pipeline_id: return False, {} pipeline_id = result_pipeline_id['result'] pipeline_definition_result = __salt__['boto_datapipeline.get_pipeline_definition']( pipeline_id, version='active', region=region, key=key, keyid=keyid, profile=profile, ) if 'error' in pipeline_definition_result: return False, {} pipeline_definition = _standardize(pipeline_definition_result['result']) pipeline_objects = pipeline_definition.get('pipelineObjects') parameter_objects = pipeline_definition.get('parameterObjects') parameter_values = pipeline_definition.get('parameterValues') present = (_recursive_compare(_cleaned(pipeline_objects), _cleaned(expected_pipeline_objects)) and _recursive_compare(parameter_objects, expected_parameter_objects) and _recursive_compare(parameter_values, expected_parameter_values)) return present, pipeline_definition
[ "def", "_pipeline_present_with_definition", "(", "name", ",", "expected_pipeline_objects", ",", "expected_parameter_objects", ",", "expected_parameter_values", ",", "region", ",", "key", ",", "keyid", ",", "profile", ")", ":", "result_pipeline_id", "=", "__salt__", "[",...
Return true if the pipeline exists and the definition matches. name The name of the pipeline. expected_pipeline_objects Pipeline objects that must match the definition. expected_parameter_objects Parameter objects that must match the definition. expected_parameter_values Parameter values that must match the definition. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Return", "true", "if", "the", "pipeline", "exists", "and", "the", "definition", "matches", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L268-L331
train
saltstack/salt
salt/states/boto_datapipeline.py
_cleaned
def _cleaned(_pipeline_objects): """Return standardized pipeline objects to be used for comparing Remove year, month, and day components of the startDateTime so that data pipelines with the same time of day but different days are considered equal. """ pipeline_objects = copy.deepcopy(_pipeline_objects) for pipeline_object in pipeline_objects: if pipeline_object['id'] == 'DefaultSchedule': for field_object in pipeline_object['fields']: if field_object['key'] == 'startDateTime': start_date_time_string = field_object['stringValue'] start_date_time = datetime.datetime.strptime(start_date_time_string, "%Y-%m-%dT%H:%M:%S") field_object['stringValue'] = start_date_time.strftime("%H:%M:%S") return pipeline_objects
python
def _cleaned(_pipeline_objects): """Return standardized pipeline objects to be used for comparing Remove year, month, and day components of the startDateTime so that data pipelines with the same time of day but different days are considered equal. """ pipeline_objects = copy.deepcopy(_pipeline_objects) for pipeline_object in pipeline_objects: if pipeline_object['id'] == 'DefaultSchedule': for field_object in pipeline_object['fields']: if field_object['key'] == 'startDateTime': start_date_time_string = field_object['stringValue'] start_date_time = datetime.datetime.strptime(start_date_time_string, "%Y-%m-%dT%H:%M:%S") field_object['stringValue'] = start_date_time.strftime("%H:%M:%S") return pipeline_objects
[ "def", "_cleaned", "(", "_pipeline_objects", ")", ":", "pipeline_objects", "=", "copy", ".", "deepcopy", "(", "_pipeline_objects", ")", "for", "pipeline_object", "in", "pipeline_objects", ":", "if", "pipeline_object", "[", "'id'", "]", "==", "'DefaultSchedule'", "...
Return standardized pipeline objects to be used for comparing Remove year, month, and day components of the startDateTime so that data pipelines with the same time of day but different days are considered equal.
[ "Return", "standardized", "pipeline", "objects", "to", "be", "used", "for", "comparing" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L334-L350
train
saltstack/salt
salt/states/boto_datapipeline.py
_recursive_compare
def _recursive_compare(v1, v2): ''' Return v1 == v2. Compares list, dict, recursively. ''' if isinstance(v1, list): if v2 is None: v2 = [] if len(v1) != len(v2): return False v1.sort(key=_id_or_key) v2.sort(key=_id_or_key) for x, y in zip(v1, v2): if not _recursive_compare(x, y): return False return True elif isinstance(v1, dict): if v2 is None: v2 = {} v1 = dict(v1) v2 = dict(v2) if sorted(v1) != sorted(v2): return False for k in v1: if not _recursive_compare(v1[k], v2[k]): return False return True else: return v1 == v2
python
def _recursive_compare(v1, v2): ''' Return v1 == v2. Compares list, dict, recursively. ''' if isinstance(v1, list): if v2 is None: v2 = [] if len(v1) != len(v2): return False v1.sort(key=_id_or_key) v2.sort(key=_id_or_key) for x, y in zip(v1, v2): if not _recursive_compare(x, y): return False return True elif isinstance(v1, dict): if v2 is None: v2 = {} v1 = dict(v1) v2 = dict(v2) if sorted(v1) != sorted(v2): return False for k in v1: if not _recursive_compare(v1[k], v2[k]): return False return True else: return v1 == v2
[ "def", "_recursive_compare", "(", "v1", ",", "v2", ")", ":", "if", "isinstance", "(", "v1", ",", "list", ")", ":", "if", "v2", "is", "None", ":", "v2", "=", "[", "]", "if", "len", "(", "v1", ")", "!=", "len", "(", "v2", ")", ":", "return", "F...
Return v1 == v2. Compares list, dict, recursively.
[ "Return", "v1", "==", "v2", ".", "Compares", "list", "dict", "recursively", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L353-L380
train
saltstack/salt
salt/states/boto_datapipeline.py
_id_or_key
def _id_or_key(list_item): ''' Return the value at key 'id' or 'key'. ''' if isinstance(list_item, dict): if 'id' in list_item: return list_item['id'] if 'key' in list_item: return list_item['key'] return list_item
python
def _id_or_key(list_item): ''' Return the value at key 'id' or 'key'. ''' if isinstance(list_item, dict): if 'id' in list_item: return list_item['id'] if 'key' in list_item: return list_item['key'] return list_item
[ "def", "_id_or_key", "(", "list_item", ")", ":", "if", "isinstance", "(", "list_item", ",", "dict", ")", ":", "if", "'id'", "in", "list_item", ":", "return", "list_item", "[", "'id'", "]", "if", "'key'", "in", "list_item", ":", "return", "list_item", "["...
Return the value at key 'id' or 'key'.
[ "Return", "the", "value", "at", "key", "id", "or", "key", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L383-L392
train
saltstack/salt
salt/states/boto_datapipeline.py
_diff
def _diff(old_pipeline_definition, new_pipeline_definition): ''' Return string diff of pipeline definitions. ''' old_pipeline_definition.pop('ResponseMetadata', None) new_pipeline_definition.pop('ResponseMetadata', None) diff = salt.utils.data.decode(difflib.unified_diff( salt.utils.json.dumps(old_pipeline_definition, indent=4).splitlines(True), salt.utils.json.dumps(new_pipeline_definition, indent=4).splitlines(True), )) return ''.join(diff)
python
def _diff(old_pipeline_definition, new_pipeline_definition): ''' Return string diff of pipeline definitions. ''' old_pipeline_definition.pop('ResponseMetadata', None) new_pipeline_definition.pop('ResponseMetadata', None) diff = salt.utils.data.decode(difflib.unified_diff( salt.utils.json.dumps(old_pipeline_definition, indent=4).splitlines(True), salt.utils.json.dumps(new_pipeline_definition, indent=4).splitlines(True), )) return ''.join(diff)
[ "def", "_diff", "(", "old_pipeline_definition", ",", "new_pipeline_definition", ")", ":", "old_pipeline_definition", ".", "pop", "(", "'ResponseMetadata'", ",", "None", ")", "new_pipeline_definition", ".", "pop", "(", "'ResponseMetadata'", ",", "None", ")", "diff", ...
Return string diff of pipeline definitions.
[ "Return", "string", "diff", "of", "pipeline", "definitions", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L395-L406
train
saltstack/salt
salt/states/boto_datapipeline.py
_standardize
def _standardize(structure): ''' Return standardized format for lists/dictionaries. Lists of dictionaries are sorted by the value of the dictionary at its primary key ('id' or 'key'). OrderedDict's are converted to basic dictionaries. ''' def mutating_helper(structure): if isinstance(structure, list): structure.sort(key=_id_or_key) for each in structure: mutating_helper(each) elif isinstance(structure, dict): structure = dict(structure) for k, v in six.iteritems(structure): mutating_helper(k) mutating_helper(v) new_structure = copy.deepcopy(structure) mutating_helper(new_structure) return new_structure
python
def _standardize(structure): ''' Return standardized format for lists/dictionaries. Lists of dictionaries are sorted by the value of the dictionary at its primary key ('id' or 'key'). OrderedDict's are converted to basic dictionaries. ''' def mutating_helper(structure): if isinstance(structure, list): structure.sort(key=_id_or_key) for each in structure: mutating_helper(each) elif isinstance(structure, dict): structure = dict(structure) for k, v in six.iteritems(structure): mutating_helper(k) mutating_helper(v) new_structure = copy.deepcopy(structure) mutating_helper(new_structure) return new_structure
[ "def", "_standardize", "(", "structure", ")", ":", "def", "mutating_helper", "(", "structure", ")", ":", "if", "isinstance", "(", "structure", ",", "list", ")", ":", "structure", ".", "sort", "(", "key", "=", "_id_or_key", ")", "for", "each", "in", "stru...
Return standardized format for lists/dictionaries. Lists of dictionaries are sorted by the value of the dictionary at its primary key ('id' or 'key'). OrderedDict's are converted to basic dictionaries.
[ "Return", "standardized", "format", "for", "lists", "/", "dictionaries", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L409-L430
train
saltstack/salt
salt/states/boto_datapipeline.py
_pipeline_objects
def _pipeline_objects(pipeline_objects_from_pillars, pipeline_object_overrides): ''' Return a list of pipeline objects that compose the pipeline pipeline_objects_from_pillars The pillar key to use for lookup pipeline_object_overrides Pipeline objects to use. Will override objects read from pillars. ''' from_pillars = copy.deepcopy(__salt__['pillar.get'](pipeline_objects_from_pillars)) from_pillars.update(pipeline_object_overrides) pipeline_objects = _standardize(_dict_to_list_ids(from_pillars)) for pipeline_object in pipeline_objects: pipeline_object['fields'] = _properties_from_dict(pipeline_object['fields']) return pipeline_objects
python
def _pipeline_objects(pipeline_objects_from_pillars, pipeline_object_overrides): ''' Return a list of pipeline objects that compose the pipeline pipeline_objects_from_pillars The pillar key to use for lookup pipeline_object_overrides Pipeline objects to use. Will override objects read from pillars. ''' from_pillars = copy.deepcopy(__salt__['pillar.get'](pipeline_objects_from_pillars)) from_pillars.update(pipeline_object_overrides) pipeline_objects = _standardize(_dict_to_list_ids(from_pillars)) for pipeline_object in pipeline_objects: pipeline_object['fields'] = _properties_from_dict(pipeline_object['fields']) return pipeline_objects
[ "def", "_pipeline_objects", "(", "pipeline_objects_from_pillars", ",", "pipeline_object_overrides", ")", ":", "from_pillars", "=", "copy", ".", "deepcopy", "(", "__salt__", "[", "'pillar.get'", "]", "(", "pipeline_objects_from_pillars", ")", ")", "from_pillars", ".", ...
Return a list of pipeline objects that compose the pipeline pipeline_objects_from_pillars The pillar key to use for lookup pipeline_object_overrides Pipeline objects to use. Will override objects read from pillars.
[ "Return", "a", "list", "of", "pipeline", "objects", "that", "compose", "the", "pipeline" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L433-L448
train
saltstack/salt
salt/states/boto_datapipeline.py
_parameter_objects
def _parameter_objects(parameter_objects_from_pillars, parameter_object_overrides): ''' Return a list of parameter objects that configure the pipeline parameter_objects_from_pillars The pillar key to use for lookup parameter_object_overrides Parameter objects to use. Will override objects read from pillars. ''' from_pillars = copy.deepcopy(__salt__['pillar.get'](parameter_objects_from_pillars)) from_pillars.update(parameter_object_overrides) parameter_objects = _standardize(_dict_to_list_ids(from_pillars)) for parameter_object in parameter_objects: parameter_object['attributes'] = _properties_from_dict(parameter_object['attributes']) return parameter_objects
python
def _parameter_objects(parameter_objects_from_pillars, parameter_object_overrides): ''' Return a list of parameter objects that configure the pipeline parameter_objects_from_pillars The pillar key to use for lookup parameter_object_overrides Parameter objects to use. Will override objects read from pillars. ''' from_pillars = copy.deepcopy(__salt__['pillar.get'](parameter_objects_from_pillars)) from_pillars.update(parameter_object_overrides) parameter_objects = _standardize(_dict_to_list_ids(from_pillars)) for parameter_object in parameter_objects: parameter_object['attributes'] = _properties_from_dict(parameter_object['attributes']) return parameter_objects
[ "def", "_parameter_objects", "(", "parameter_objects_from_pillars", ",", "parameter_object_overrides", ")", ":", "from_pillars", "=", "copy", ".", "deepcopy", "(", "__salt__", "[", "'pillar.get'", "]", "(", "parameter_objects_from_pillars", ")", ")", "from_pillars", "."...
Return a list of parameter objects that configure the pipeline parameter_objects_from_pillars The pillar key to use for lookup parameter_object_overrides Parameter objects to use. Will override objects read from pillars.
[ "Return", "a", "list", "of", "parameter", "objects", "that", "configure", "the", "pipeline" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L451-L466
train
saltstack/salt
salt/states/boto_datapipeline.py
_parameter_values
def _parameter_values(parameter_values_from_pillars, parameter_value_overrides): ''' Return a dictionary of parameter values that configure the pipeline parameter_values_from_pillars The pillar key to use for lookup parameter_value_overrides Parameter values to use. Will override values read from pillars. ''' from_pillars = copy.deepcopy(__salt__['pillar.get'](parameter_values_from_pillars)) from_pillars.update(parameter_value_overrides) parameter_values = _standardize(from_pillars) return _properties_from_dict(parameter_values, key_name='id')
python
def _parameter_values(parameter_values_from_pillars, parameter_value_overrides): ''' Return a dictionary of parameter values that configure the pipeline parameter_values_from_pillars The pillar key to use for lookup parameter_value_overrides Parameter values to use. Will override values read from pillars. ''' from_pillars = copy.deepcopy(__salt__['pillar.get'](parameter_values_from_pillars)) from_pillars.update(parameter_value_overrides) parameter_values = _standardize(from_pillars) return _properties_from_dict(parameter_values, key_name='id')
[ "def", "_parameter_values", "(", "parameter_values_from_pillars", ",", "parameter_value_overrides", ")", ":", "from_pillars", "=", "copy", ".", "deepcopy", "(", "__salt__", "[", "'pillar.get'", "]", "(", "parameter_values_from_pillars", ")", ")", "from_pillars", ".", ...
Return a dictionary of parameter values that configure the pipeline parameter_values_from_pillars The pillar key to use for lookup parameter_value_overrides Parameter values to use. Will override values read from pillars.
[ "Return", "a", "dictionary", "of", "parameter", "values", "that", "configure", "the", "pipeline" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L469-L482
train
saltstack/salt
salt/states/boto_datapipeline.py
_dict_to_list_ids
def _dict_to_list_ids(objects): ''' Convert a dictionary to a list of dictionaries, where each element has a key value pair {'id': key}. This makes it easy to override pillar values while still satisfying the boto api. ''' list_with_ids = [] for key, value in six.iteritems(objects): element = {'id': key} element.update(value) list_with_ids.append(element) return list_with_ids
python
def _dict_to_list_ids(objects): ''' Convert a dictionary to a list of dictionaries, where each element has a key value pair {'id': key}. This makes it easy to override pillar values while still satisfying the boto api. ''' list_with_ids = [] for key, value in six.iteritems(objects): element = {'id': key} element.update(value) list_with_ids.append(element) return list_with_ids
[ "def", "_dict_to_list_ids", "(", "objects", ")", ":", "list_with_ids", "=", "[", "]", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "objects", ")", ":", "element", "=", "{", "'id'", ":", "key", "}", "element", ".", "update", "(", "v...
Convert a dictionary to a list of dictionaries, where each element has a key value pair {'id': key}. This makes it easy to override pillar values while still satisfying the boto api.
[ "Convert", "a", "dictionary", "to", "a", "list", "of", "dictionaries", "where", "each", "element", "has", "a", "key", "value", "pair", "{", "id", ":", "key", "}", ".", "This", "makes", "it", "easy", "to", "override", "pillar", "values", "while", "still",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L485-L496
train
saltstack/salt
salt/states/boto_datapipeline.py
_properties_from_dict
def _properties_from_dict(d, key_name='key'): ''' Transforms dictionary into pipeline object properties. The output format conforms to boto's specification. Example input: { 'a': '1', 'b': { 'ref': '2' }, } Example output: [ { 'key': 'a', 'stringValue': '1', }, { 'key': 'b', 'refValue': '2', }, ] ''' fields = [] for key, value in six.iteritems(d): if isinstance(value, dict): fields.append({ key_name: key, 'refValue': value['ref'], }) else: fields.append({ key_name: key, 'stringValue': value, }) return fields
python
def _properties_from_dict(d, key_name='key'): ''' Transforms dictionary into pipeline object properties. The output format conforms to boto's specification. Example input: { 'a': '1', 'b': { 'ref': '2' }, } Example output: [ { 'key': 'a', 'stringValue': '1', }, { 'key': 'b', 'refValue': '2', }, ] ''' fields = [] for key, value in six.iteritems(d): if isinstance(value, dict): fields.append({ key_name: key, 'refValue': value['ref'], }) else: fields.append({ key_name: key, 'stringValue': value, }) return fields
[ "def", "_properties_from_dict", "(", "d", ",", "key_name", "=", "'key'", ")", ":", "fields", "=", "[", "]", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "d", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "fie...
Transforms dictionary into pipeline object properties. The output format conforms to boto's specification. Example input: { 'a': '1', 'b': { 'ref': '2' }, } Example output: [ { 'key': 'a', 'stringValue': '1', }, { 'key': 'b', 'refValue': '2', }, ]
[ "Transforms", "dictionary", "into", "pipeline", "object", "properties", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L499-L537
train
saltstack/salt
salt/states/boto_datapipeline.py
absent
def absent(name, region=None, key=None, keyid=None, profile=None): ''' Ensure a pipeline with the service_name does not exist name Name of the service to ensure a data pipeline does not exist for. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} result_pipeline_id = __salt__['boto_datapipeline.pipeline_id_from_name']( name, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' not in result_pipeline_id: pipeline_id = result_pipeline_id['result'] if __opts__['test']: ret['comment'] = 'Data pipeline {0} set to be deleted.'.format(name) ret['result'] = None return ret else: __salt__['boto_datapipeline.delete_pipeline']( pipeline_id, region=region, key=key, keyid=keyid, profile=profile, ) ret['changes']['old'] = {'pipeline_id': pipeline_id} ret['changes']['new'] = None else: ret['comment'] = 'AWS data pipeline {0} absent.'.format(name) return ret
python
def absent(name, region=None, key=None, keyid=None, profile=None): ''' Ensure a pipeline with the service_name does not exist name Name of the service to ensure a data pipeline does not exist for. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} result_pipeline_id = __salt__['boto_datapipeline.pipeline_id_from_name']( name, region=region, key=key, keyid=keyid, profile=profile, ) if 'error' not in result_pipeline_id: pipeline_id = result_pipeline_id['result'] if __opts__['test']: ret['comment'] = 'Data pipeline {0} set to be deleted.'.format(name) ret['result'] = None return ret else: __salt__['boto_datapipeline.delete_pipeline']( pipeline_id, region=region, key=key, keyid=keyid, profile=profile, ) ret['changes']['old'] = {'pipeline_id': pipeline_id} ret['changes']['new'] = None else: ret['comment'] = 'AWS data pipeline {0} absent.'.format(name) return ret
[ "def", "absent", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''"...
Ensure a pipeline with the service_name does not exist name Name of the service to ensure a data pipeline does not exist for. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Ensure", "a", "pipeline", "with", "the", "service_name", "does", "not", "exist" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L540-L588
train
saltstack/salt
salt/serializers/json.py
deserialize
def deserialize(stream_or_string, **options): ''' Deserialize any string or stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower json/simplejson module. ''' try: if not isinstance(stream_or_string, (bytes, six.string_types)): return salt.utils.json.load( stream_or_string, _json_module=_json, **options) if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode('utf-8') return salt.utils.json.loads(stream_or_string, _json_module=_json) except Exception as error: raise DeserializationError(error)
python
def deserialize(stream_or_string, **options): ''' Deserialize any string or stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower json/simplejson module. ''' try: if not isinstance(stream_or_string, (bytes, six.string_types)): return salt.utils.json.load( stream_or_string, _json_module=_json, **options) if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode('utf-8') return salt.utils.json.loads(stream_or_string, _json_module=_json) except Exception as error: raise DeserializationError(error)
[ "def", "deserialize", "(", "stream_or_string", ",", "*", "*", "options", ")", ":", "try", ":", "if", "not", "isinstance", "(", "stream_or_string", ",", "(", "bytes", ",", "six", ".", "string_types", ")", ")", ":", "return", "salt", ".", "utils", ".", "...
Deserialize any string or stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower json/simplejson module.
[ "Deserialize", "any", "string", "or", "stream", "like", "object", "into", "a", "Python", "data", "structure", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/json.py#L30-L48
train
saltstack/salt
salt/serializers/json.py
serialize
def serialize(obj, **options): ''' Serialize Python data to JSON. :param obj: the data structure to serialize :param options: options given to lower json/simplejson module. ''' try: if 'fp' in options: return salt.utils.json.dump(obj, _json_module=_json, **options) else: return salt.utils.json.dumps(obj, _json_module=_json, **options) except Exception as error: raise SerializationError(error)
python
def serialize(obj, **options): ''' Serialize Python data to JSON. :param obj: the data structure to serialize :param options: options given to lower json/simplejson module. ''' try: if 'fp' in options: return salt.utils.json.dump(obj, _json_module=_json, **options) else: return salt.utils.json.dumps(obj, _json_module=_json, **options) except Exception as error: raise SerializationError(error)
[ "def", "serialize", "(", "obj", ",", "*", "*", "options", ")", ":", "try", ":", "if", "'fp'", "in", "options", ":", "return", "salt", ".", "utils", ".", "json", ".", "dump", "(", "obj", ",", "_json_module", "=", "_json", ",", "*", "*", "options", ...
Serialize Python data to JSON. :param obj: the data structure to serialize :param options: options given to lower json/simplejson module.
[ "Serialize", "Python", "data", "to", "JSON", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/json.py#L51-L65
train
saltstack/salt
salt/states/mysql_database.py
present
def present(name, character_set=None, collate=None, **connection_args): ''' Ensure that the named database is present with the specified properties name The name of the database to manage ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Database {0} is already present'.format(name)} # check if database exists existing = __salt__['mysql.db_get'](name, **connection_args) if existing: alter = False if character_set and character_set != existing.get('character_set'): log.debug('character set differes from %s : %s', character_set, existing.get('character_set')) alter = True if collate and collate != existing.get('collate'): log.debug('collate set differs from %s : %s', collate, existing.get('collate')) alter = True if alter: __salt__['mysql.alter_db']( name, character_set=character_set, collate=collate, **connection_args) current = __salt__['mysql.db_get'](name, **connection_args) if existing.get('collate', None) != current.get('collate', None): ret['changes'].update({'collate': { 'before': existing.get('collate', None), 'now': current.get('collate', None)}}) if existing.get('character_set', None) != current.get('character_set', None): ret['changes'].update({'character_set': { 'before': existing.get('character_set', None), 'now': current.get('character_set', None)}}) return ret else: err = _get_mysql_error() if err is not None: ret['comment'] = err ret['result'] = False return ret if __opts__['test']: ret['result'] = None ret['comment'] = ('Database {0} is not present and needs to be created' ).format(name) return ret # The database is not present, make it! if __salt__['mysql.db_create']( name, character_set=character_set, collate=collate, **connection_args): ret['comment'] = 'The database {0} has been created'.format(name) ret['changes'][name] = 'Present' else: ret['comment'] = 'Failed to create database {0}'.format(name) err = _get_mysql_error() if err is not None: ret['comment'] += ' ({0})'.format(err) ret['result'] = False return ret
python
def present(name, character_set=None, collate=None, **connection_args): ''' Ensure that the named database is present with the specified properties name The name of the database to manage ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Database {0} is already present'.format(name)} # check if database exists existing = __salt__['mysql.db_get'](name, **connection_args) if existing: alter = False if character_set and character_set != existing.get('character_set'): log.debug('character set differes from %s : %s', character_set, existing.get('character_set')) alter = True if collate and collate != existing.get('collate'): log.debug('collate set differs from %s : %s', collate, existing.get('collate')) alter = True if alter: __salt__['mysql.alter_db']( name, character_set=character_set, collate=collate, **connection_args) current = __salt__['mysql.db_get'](name, **connection_args) if existing.get('collate', None) != current.get('collate', None): ret['changes'].update({'collate': { 'before': existing.get('collate', None), 'now': current.get('collate', None)}}) if existing.get('character_set', None) != current.get('character_set', None): ret['changes'].update({'character_set': { 'before': existing.get('character_set', None), 'now': current.get('character_set', None)}}) return ret else: err = _get_mysql_error() if err is not None: ret['comment'] = err ret['result'] = False return ret if __opts__['test']: ret['result'] = None ret['comment'] = ('Database {0} is not present and needs to be created' ).format(name) return ret # The database is not present, make it! if __salt__['mysql.db_create']( name, character_set=character_set, collate=collate, **connection_args): ret['comment'] = 'The database {0} has been created'.format(name) ret['changes'][name] = 'Present' else: ret['comment'] = 'Failed to create database {0}'.format(name) err = _get_mysql_error() if err is not None: ret['comment'] += ' ({0})'.format(err) ret['result'] = False return ret
[ "def", "present", "(", "name", ",", "character_set", "=", "None", ",", "collate", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "...
Ensure that the named database is present with the specified properties name The name of the database to manage
[ "Ensure", "that", "the", "named", "database", "is", "present", "with", "the", "specified", "properties" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mysql_database.py#L43-L105
train
saltstack/salt
salt/states/mysql_database.py
absent
def absent(name, **connection_args): ''' Ensure that the named database is absent name The name of the database to remove ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if db exists and remove it if __salt__['mysql.db_exists'](name, **connection_args): if __opts__['test']: ret['result'] = None ret['comment'] = \ 'Database {0} is present and needs to be removed'.format(name) return ret if __salt__['mysql.db_remove'](name, **connection_args): ret['comment'] = 'Database {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret else: err = _get_mysql_error() if err is not None: ret['comment'] = 'Unable to remove database {0} ' \ '({1})'.format(name, err) ret['result'] = False return ret else: err = _get_mysql_error() if err is not None: ret['comment'] = err ret['result'] = False return ret # fallback ret['comment'] = ('Database {0} is not present, so it cannot be removed' ).format(name) return ret
python
def absent(name, **connection_args): ''' Ensure that the named database is absent name The name of the database to remove ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if db exists and remove it if __salt__['mysql.db_exists'](name, **connection_args): if __opts__['test']: ret['result'] = None ret['comment'] = \ 'Database {0} is present and needs to be removed'.format(name) return ret if __salt__['mysql.db_remove'](name, **connection_args): ret['comment'] = 'Database {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret else: err = _get_mysql_error() if err is not None: ret['comment'] = 'Unable to remove database {0} ' \ '({1})'.format(name, err) ret['result'] = False return ret else: err = _get_mysql_error() if err is not None: ret['comment'] = err ret['result'] = False return ret # fallback ret['comment'] = ('Database {0} is not present, so it cannot be removed' ).format(name) return ret
[ "def", "absent", "(", "name", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "#check if db exists and remove it", "if", ...
Ensure that the named database is absent name The name of the database to remove
[ "Ensure", "that", "the", "named", "database", "is", "absent" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mysql_database.py#L108-L148
train
saltstack/salt
salt/runners/net.py
_get_net_runner_opts
def _get_net_runner_opts(): ''' Return the net.find runner options. ''' runner_opts = __opts__.get('runners', {}).get('net.find', {}) return { 'target': runner_opts.get('target', _DEFAULT_TARGET), 'expr_form': runner_opts.get('expr_form', _DEFAULT_EXPR_FORM), 'ignore_interfaces': runner_opts.get('ignore_interfaces', _DEFAULT_IGNORE_INTF), 'display': runner_opts.get('display', _DEFAULT_DISPLAY), 'outputter': runner_opts.get('outputter', _DEFAULT_OUTPUTTER), }
python
def _get_net_runner_opts(): ''' Return the net.find runner options. ''' runner_opts = __opts__.get('runners', {}).get('net.find', {}) return { 'target': runner_opts.get('target', _DEFAULT_TARGET), 'expr_form': runner_opts.get('expr_form', _DEFAULT_EXPR_FORM), 'ignore_interfaces': runner_opts.get('ignore_interfaces', _DEFAULT_IGNORE_INTF), 'display': runner_opts.get('display', _DEFAULT_DISPLAY), 'outputter': runner_opts.get('outputter', _DEFAULT_OUTPUTTER), }
[ "def", "_get_net_runner_opts", "(", ")", ":", "runner_opts", "=", "__opts__", ".", "get", "(", "'runners'", ",", "{", "}", ")", ".", "get", "(", "'net.find'", ",", "{", "}", ")", "return", "{", "'target'", ":", "runner_opts", ".", "get", "(", "'target'...
Return the net.find runner options.
[ "Return", "the", "net", ".", "find", "runner", "options", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L121-L132
train
saltstack/salt
salt/runners/net.py
_get_mine
def _get_mine(fun): ''' Return the mine function from all the targeted minions. Just a small helper to avoid redundant pieces of code. ''' if fun in _CACHE and _CACHE[fun]: return _CACHE[fun] net_runner_opts = _get_net_runner_opts() _CACHE[fun] = __salt__['mine.get'](net_runner_opts.get('target'), fun, tgt_type=net_runner_opts.get('expr_form')) return _CACHE[fun]
python
def _get_mine(fun): ''' Return the mine function from all the targeted minions. Just a small helper to avoid redundant pieces of code. ''' if fun in _CACHE and _CACHE[fun]: return _CACHE[fun] net_runner_opts = _get_net_runner_opts() _CACHE[fun] = __salt__['mine.get'](net_runner_opts.get('target'), fun, tgt_type=net_runner_opts.get('expr_form')) return _CACHE[fun]
[ "def", "_get_mine", "(", "fun", ")", ":", "if", "fun", "in", "_CACHE", "and", "_CACHE", "[", "fun", "]", ":", "return", "_CACHE", "[", "fun", "]", "net_runner_opts", "=", "_get_net_runner_opts", "(", ")", "_CACHE", "[", "fun", "]", "=", "__salt__", "["...
Return the mine function from all the targeted minions. Just a small helper to avoid redundant pieces of code.
[ "Return", "the", "mine", "function", "from", "all", "the", "targeted", "minions", ".", "Just", "a", "small", "helper", "to", "avoid", "redundant", "pieces", "of", "code", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L135-L146
train
saltstack/salt
salt/runners/net.py
_display_runner
def _display_runner(rows, labels, title, display=_DEFAULT_DISPLAY): ''' Display or return the rows. ''' if display: net_runner_opts = _get_net_runner_opts() if net_runner_opts.get('outputter') == 'table': ret = salt.output.out_format({'rows': rows, 'labels': labels}, 'table', __opts__, title=title, rows_key='rows', labels_key='labels') else: ret = salt.output.out_format(rows, net_runner_opts.get('outputter'), __opts__) print(ret) else: return rows
python
def _display_runner(rows, labels, title, display=_DEFAULT_DISPLAY): ''' Display or return the rows. ''' if display: net_runner_opts = _get_net_runner_opts() if net_runner_opts.get('outputter') == 'table': ret = salt.output.out_format({'rows': rows, 'labels': labels}, 'table', __opts__, title=title, rows_key='rows', labels_key='labels') else: ret = salt.output.out_format(rows, net_runner_opts.get('outputter'), __opts__) print(ret) else: return rows
[ "def", "_display_runner", "(", "rows", ",", "labels", ",", "title", ",", "display", "=", "_DEFAULT_DISPLAY", ")", ":", "if", "display", ":", "net_runner_opts", "=", "_get_net_runner_opts", "(", ")", "if", "net_runner_opts", ".", "get", "(", "'outputter'", ")",...
Display or return the rows.
[ "Display", "or", "return", "the", "rows", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L149-L168
train
saltstack/salt
salt/runners/net.py
_find_interfaces_ip
def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, mac) except AddrFormatError: return ('', '', []) all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.ipaddrs') for device, device_interfaces in six.iteritems(all_interfaces): if not device_interfaces.get('result', False): continue for interface, interface_details in six.iteritems(device_interfaces.get('out', {})): try: interface_mac = napalm_helpers.convert(napalm_helpers.mac, interface_details.get('mac_address')) except AddrFormatError: continue if mac != interface_mac: continue interface_ipaddrs = all_ipaddrs.get(device, {}).get('out', {}).get(interface, {}) ip_addresses = interface_ipaddrs.get('ipv4', {}) ip_addresses.update(interface_ipaddrs.get('ipv6', {})) interface_ips = ['{0}/{1}'.format(ip_addr, addr_details.get('prefix_length', '32')) for ip_addr, addr_details in six.iteritems(ip_addresses)] return device, interface, interface_ips return ('', '', [])
python
def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, mac) except AddrFormatError: return ('', '', []) all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.ipaddrs') for device, device_interfaces in six.iteritems(all_interfaces): if not device_interfaces.get('result', False): continue for interface, interface_details in six.iteritems(device_interfaces.get('out', {})): try: interface_mac = napalm_helpers.convert(napalm_helpers.mac, interface_details.get('mac_address')) except AddrFormatError: continue if mac != interface_mac: continue interface_ipaddrs = all_ipaddrs.get(device, {}).get('out', {}).get(interface, {}) ip_addresses = interface_ipaddrs.get('ipv4', {}) ip_addresses.update(interface_ipaddrs.get('ipv6', {})) interface_ips = ['{0}/{1}'.format(ip_addr, addr_details.get('prefix_length', '32')) for ip_addr, addr_details in six.iteritems(ip_addresses)] return device, interface, interface_ips return ('', '', [])
[ "def", "_find_interfaces_ip", "(", "mac", ")", ":", "try", ":", "mac", "=", "napalm_helpers", ".", "convert", "(", "napalm_helpers", ".", "mac", ",", "mac", ")", "except", "AddrFormatError", ":", "return", "(", "''", ",", "''", ",", "[", "]", ")", "all...
Helper to search the interfaces IPs using the MAC address.
[ "Helper", "to", "search", "the", "interfaces", "IPs", "using", "the", "MAC", "address", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L183-L213
train
saltstack/salt
salt/runners/net.py
_find_interfaces_mac
def _find_interfaces_mac(ip): # pylint: disable=invalid-name ''' Helper to get the interfaces hardware address using the IP Address. ''' all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.ipaddrs') for device, device_ipaddrs in six.iteritems(all_ipaddrs): if not device_ipaddrs.get('result', False): continue for interface, interface_ipaddrs in six.iteritems(device_ipaddrs.get('out', {})): ip_addresses = interface_ipaddrs.get('ipv4', {}).keys() ip_addresses.extend(interface_ipaddrs.get('ipv6', {}).keys()) for ipaddr in ip_addresses: if ip != ipaddr: continue interface_mac = all_interfaces.get(device, {}).get('out', {}).get(interface, {}).get('mac_address', '') return device, interface, interface_mac return ('', '', '')
python
def _find_interfaces_mac(ip): # pylint: disable=invalid-name ''' Helper to get the interfaces hardware address using the IP Address. ''' all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.ipaddrs') for device, device_ipaddrs in six.iteritems(all_ipaddrs): if not device_ipaddrs.get('result', False): continue for interface, interface_ipaddrs in six.iteritems(device_ipaddrs.get('out', {})): ip_addresses = interface_ipaddrs.get('ipv4', {}).keys() ip_addresses.extend(interface_ipaddrs.get('ipv6', {}).keys()) for ipaddr in ip_addresses: if ip != ipaddr: continue interface_mac = all_interfaces.get(device, {}).get('out', {}).get(interface, {}).get('mac_address', '') return device, interface, interface_mac return ('', '', '')
[ "def", "_find_interfaces_mac", "(", "ip", ")", ":", "# pylint: disable=invalid-name", "all_interfaces", "=", "_get_mine", "(", "'net.interfaces'", ")", "all_ipaddrs", "=", "_get_mine", "(", "'net.ipaddrs'", ")", "for", "device", ",", "device_ipaddrs", "in", "six", "...
Helper to get the interfaces hardware address using the IP Address.
[ "Helper", "to", "get", "the", "interfaces", "hardware", "address", "using", "the", "IP", "Address", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L216-L235
train
saltstack/salt
salt/runners/net.py
interfaces
def interfaces(device=None, interface=None, title=None, pattern=None, ipnet=None, best=True, display=_DEFAULT_DISPLAY): ''' Search for interfaces details in the following mine functions: - net.interfaces - net.ipaddrs Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return interfaces that contain a certain pattern in their description. ipnet Return interfaces whose IP networks associated include this IP network. best: ``True`` When ``ipnet`` is specified, this argument says if the runner should return only the best match (the output will contain at most one row). Default: ``True`` (return only the best match). display: True Display on the screen or return structured object? Default: ``True`` (return on the CLI). title Display a custom title for the table. CLI Example: .. code-block:: bash $ sudo salt-run net.interfaces interface=vt-0/0/10 Output Example: .. code-block:: text Details for interface xe-0/0/0 _________________________________________________________________________________________________________________ | Device | Interface | Interface Description | UP | Enabled | Speed [Mbps] | MAC Address | IP Addresses | _________________________________________________________________________________________________________________ | edge01.bjm01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.flw01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.pos01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.oua01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ ''' def _ipnet_belongs(net): ''' Helper to tell if a IP address or network belong to a certain network. ''' if net == '0.0.0.0/0': return False net_obj = _get_network_obj(net) if not net_obj: return False return ipnet in net_obj or net_obj in ipnet labels = { 'device': 'Device', 'interface': 'Interface', 'interface_description': 'Interface Description', 'is_up': 'UP', 'is_enabled': 'Enabled', 'speed': 'Speed [Mbps]', 'mac': 'MAC Address', 'ips': 'IP Addresses' } rows = [] net_runner_opts = _get_net_runner_opts() if pattern: title = 'Pattern "{0}" found in the description of the following interfaces'.format(pattern) if not title: title = 'Details' if interface: title += ' for interface {0}'.format(interface) else: title += ' for all interfaces' if device: title += ' on device {0}'.format(device) if ipnet: title += ' that include network {net}'.format(net=six.text_type(ipnet)) if best: title += ' - only best match returned' all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.ipaddrs') if device: all_interfaces = {device: all_interfaces.get(device, {})} if ipnet and not isinstance(ipnet, IPNetwork): ipnet = _get_network_obj(ipnet) best_row = {} best_net_match = None for device, net_interfaces_out in six.iteritems(all_interfaces): # pylint: disable=too-many-nested-blocks if not net_interfaces_out: continue if not net_interfaces_out.get('result', False): continue selected_device_interfaces = net_interfaces_out.get('out', {}) if interface: selected_device_interfaces = {interface: selected_device_interfaces.get(interface, {})} for interface_name, interface_details in six.iteritems(selected_device_interfaces): if not interface_details: continue if ipnet and interface_name in net_runner_opts.get('ignore_interfaces'): continue interface_description = (interface_details.get('description', '') or '') if pattern: if pattern.lower() not in interface_description.lower(): continue if not all_ipaddrs.get(device, {}).get('result', False): continue ips = [] device_entry = { 'device': device, 'interface': interface_name, 'interface_description': interface_description, 'is_up': (interface_details.get('is_up', '') or ''), 'is_enabled': (interface_details.get('is_enabled', '') or ''), 'speed': (interface_details.get('speed', '') or ''), 'mac': napalm_helpers.convert(napalm_helpers.mac, (interface_details.get('mac_address', '') or '')), 'ips': [] } intf_entry_found = False for intrf, interface_ips in six.iteritems(all_ipaddrs.get(device, {}).get('out', {})): if intrf.split('.')[0] == interface_name: ip_addresses = interface_ips.get('ipv4', {}) # all IPv4 addresses ip_addresses.update(interface_ips.get('ipv6', {})) # and all IPv6 addresses ips = [ '{0}/{1}'.format( ip_addr, addr_details.get('prefix_length', '32') ) for ip_addr, addr_details in six.iteritems(ip_addresses) ] interf_entry = {} interf_entry.update(device_entry) interf_entry['ips'] = ips if display: interf_entry['ips'] = '\n'.join(interf_entry['ips']) if ipnet: inet_ips = [ six.text_type(ip) for ip in ips if _ipnet_belongs(ip) ] # filter and get only IP include ipnet if inet_ips: # if any if best: # determine the global best match compare = [best_net_match] compare.extend(list(map(_get_network_obj, inet_ips))) new_best_net_match = max(compare) if new_best_net_match != best_net_match: best_net_match = new_best_net_match best_row = interf_entry else: # or include all intf_entry_found = True rows.append(interf_entry) else: intf_entry_found = True rows.append(interf_entry) if not intf_entry_found and not ipnet: interf_entry = {} interf_entry.update(device_entry) if display: interf_entry['ips'] = '' rows.append(interf_entry) if ipnet and best and best_row: rows = [best_row] return _display_runner(rows, labels, title, display=display)
python
def interfaces(device=None, interface=None, title=None, pattern=None, ipnet=None, best=True, display=_DEFAULT_DISPLAY): ''' Search for interfaces details in the following mine functions: - net.interfaces - net.ipaddrs Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return interfaces that contain a certain pattern in their description. ipnet Return interfaces whose IP networks associated include this IP network. best: ``True`` When ``ipnet`` is specified, this argument says if the runner should return only the best match (the output will contain at most one row). Default: ``True`` (return only the best match). display: True Display on the screen or return structured object? Default: ``True`` (return on the CLI). title Display a custom title for the table. CLI Example: .. code-block:: bash $ sudo salt-run net.interfaces interface=vt-0/0/10 Output Example: .. code-block:: text Details for interface xe-0/0/0 _________________________________________________________________________________________________________________ | Device | Interface | Interface Description | UP | Enabled | Speed [Mbps] | MAC Address | IP Addresses | _________________________________________________________________________________________________________________ | edge01.bjm01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.flw01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.pos01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.oua01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ ''' def _ipnet_belongs(net): ''' Helper to tell if a IP address or network belong to a certain network. ''' if net == '0.0.0.0/0': return False net_obj = _get_network_obj(net) if not net_obj: return False return ipnet in net_obj or net_obj in ipnet labels = { 'device': 'Device', 'interface': 'Interface', 'interface_description': 'Interface Description', 'is_up': 'UP', 'is_enabled': 'Enabled', 'speed': 'Speed [Mbps]', 'mac': 'MAC Address', 'ips': 'IP Addresses' } rows = [] net_runner_opts = _get_net_runner_opts() if pattern: title = 'Pattern "{0}" found in the description of the following interfaces'.format(pattern) if not title: title = 'Details' if interface: title += ' for interface {0}'.format(interface) else: title += ' for all interfaces' if device: title += ' on device {0}'.format(device) if ipnet: title += ' that include network {net}'.format(net=six.text_type(ipnet)) if best: title += ' - only best match returned' all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.ipaddrs') if device: all_interfaces = {device: all_interfaces.get(device, {})} if ipnet and not isinstance(ipnet, IPNetwork): ipnet = _get_network_obj(ipnet) best_row = {} best_net_match = None for device, net_interfaces_out in six.iteritems(all_interfaces): # pylint: disable=too-many-nested-blocks if not net_interfaces_out: continue if not net_interfaces_out.get('result', False): continue selected_device_interfaces = net_interfaces_out.get('out', {}) if interface: selected_device_interfaces = {interface: selected_device_interfaces.get(interface, {})} for interface_name, interface_details in six.iteritems(selected_device_interfaces): if not interface_details: continue if ipnet and interface_name in net_runner_opts.get('ignore_interfaces'): continue interface_description = (interface_details.get('description', '') or '') if pattern: if pattern.lower() not in interface_description.lower(): continue if not all_ipaddrs.get(device, {}).get('result', False): continue ips = [] device_entry = { 'device': device, 'interface': interface_name, 'interface_description': interface_description, 'is_up': (interface_details.get('is_up', '') or ''), 'is_enabled': (interface_details.get('is_enabled', '') or ''), 'speed': (interface_details.get('speed', '') or ''), 'mac': napalm_helpers.convert(napalm_helpers.mac, (interface_details.get('mac_address', '') or '')), 'ips': [] } intf_entry_found = False for intrf, interface_ips in six.iteritems(all_ipaddrs.get(device, {}).get('out', {})): if intrf.split('.')[0] == interface_name: ip_addresses = interface_ips.get('ipv4', {}) # all IPv4 addresses ip_addresses.update(interface_ips.get('ipv6', {})) # and all IPv6 addresses ips = [ '{0}/{1}'.format( ip_addr, addr_details.get('prefix_length', '32') ) for ip_addr, addr_details in six.iteritems(ip_addresses) ] interf_entry = {} interf_entry.update(device_entry) interf_entry['ips'] = ips if display: interf_entry['ips'] = '\n'.join(interf_entry['ips']) if ipnet: inet_ips = [ six.text_type(ip) for ip in ips if _ipnet_belongs(ip) ] # filter and get only IP include ipnet if inet_ips: # if any if best: # determine the global best match compare = [best_net_match] compare.extend(list(map(_get_network_obj, inet_ips))) new_best_net_match = max(compare) if new_best_net_match != best_net_match: best_net_match = new_best_net_match best_row = interf_entry else: # or include all intf_entry_found = True rows.append(interf_entry) else: intf_entry_found = True rows.append(interf_entry) if not intf_entry_found and not ipnet: interf_entry = {} interf_entry.update(device_entry) if display: interf_entry['ips'] = '' rows.append(interf_entry) if ipnet and best and best_row: rows = [best_row] return _display_runner(rows, labels, title, display=display)
[ "def", "interfaces", "(", "device", "=", "None", ",", "interface", "=", "None", ",", "title", "=", "None", ",", "pattern", "=", "None", ",", "ipnet", "=", "None", ",", "best", "=", "True", ",", "display", "=", "_DEFAULT_DISPLAY", ")", ":", "def", "_i...
Search for interfaces details in the following mine functions: - net.interfaces - net.ipaddrs Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return interfaces that contain a certain pattern in their description. ipnet Return interfaces whose IP networks associated include this IP network. best: ``True`` When ``ipnet`` is specified, this argument says if the runner should return only the best match (the output will contain at most one row). Default: ``True`` (return only the best match). display: True Display on the screen or return structured object? Default: ``True`` (return on the CLI). title Display a custom title for the table. CLI Example: .. code-block:: bash $ sudo salt-run net.interfaces interface=vt-0/0/10 Output Example: .. code-block:: text Details for interface xe-0/0/0 _________________________________________________________________________________________________________________ | Device | Interface | Interface Description | UP | Enabled | Speed [Mbps] | MAC Address | IP Addresses | _________________________________________________________________________________________________________________ | edge01.bjm01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.flw01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.pos01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________ | edge01.oua01 | vt-0/0/10 | | True | True | 1000 | | | _________________________________________________________________________________________________________________
[ "Search", "for", "interfaces", "details", "in", "the", "following", "mine", "functions", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L243-L431
train
saltstack/salt
salt/runners/net.py
findarp
def findarp(device=None, interface=None, mac=None, ip=None, display=_DEFAULT_DISPLAY): # pylint: disable=invalid-name ''' Search for entries in the ARP tables using the following mine functions: - net.arp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. mac Search using a specific MAC Address. ip Search using a specific IP Address. display: ``True`` Display on the screen or return structured object? Default: ``True``, will return on the CLI. CLI Example: .. code-block:: bash $ sudo salt-run net.findarp mac=8C:60:0F:78:EC:41 Output Example: .. code-block:: text ARP Entries for MAC 8C:60:0F:78:EC:41 ________________________________________________________________________________ | Device | Interface | MAC | IP | Age | ________________________________________________________________________________ | edge01.bjm01 | irb.171 [ae0.171] | 8C:60:0F:78:EC:41 | 172.172.17.19 | 956.0 | ________________________________________________________________________________ ''' labels = { 'device': 'Device', 'interface': 'Interface', 'mac': 'MAC', 'ip': 'IP', 'age': 'Age' } rows = [] all_arp = _get_mine('net.arp') title = "ARP Entries" if device: title += ' on device {device}'.format(device=device) if interface: title += ' on interface {interf}'.format(interf=interface) if ip: title += ' for IP {ip}'.format(ip=ip) if mac: title += ' for MAC {mac}'.format(mac=mac) if device: all_arp = {device: all_arp.get(device)} for device, device_arp in six.iteritems(all_arp): if not device_arp: continue if not device_arp.get('result', False): continue arp_table = device_arp.get('out', []) for arp_entry in arp_table: if ((mac and arp_entry.get('mac', '').lower() == mac.lower()) or # pylint: disable=too-many-boolean-expressions (interface and interface in arp_entry.get('interface', '')) or (ip and napalm_helpers.convert(napalm_helpers.ip, arp_entry.get('ip', '')) == napalm_helpers.convert(napalm_helpers.ip, ip))): rows.append({ 'device': device, 'interface': arp_entry.get('interface'), 'mac': napalm_helpers.convert(napalm_helpers.mac, arp_entry.get('mac')), 'ip': napalm_helpers.convert(napalm_helpers.ip, arp_entry.get('ip')), 'age': arp_entry.get('age') }) return _display_runner(rows, labels, title, display=display)
python
def findarp(device=None, interface=None, mac=None, ip=None, display=_DEFAULT_DISPLAY): # pylint: disable=invalid-name ''' Search for entries in the ARP tables using the following mine functions: - net.arp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. mac Search using a specific MAC Address. ip Search using a specific IP Address. display: ``True`` Display on the screen or return structured object? Default: ``True``, will return on the CLI. CLI Example: .. code-block:: bash $ sudo salt-run net.findarp mac=8C:60:0F:78:EC:41 Output Example: .. code-block:: text ARP Entries for MAC 8C:60:0F:78:EC:41 ________________________________________________________________________________ | Device | Interface | MAC | IP | Age | ________________________________________________________________________________ | edge01.bjm01 | irb.171 [ae0.171] | 8C:60:0F:78:EC:41 | 172.172.17.19 | 956.0 | ________________________________________________________________________________ ''' labels = { 'device': 'Device', 'interface': 'Interface', 'mac': 'MAC', 'ip': 'IP', 'age': 'Age' } rows = [] all_arp = _get_mine('net.arp') title = "ARP Entries" if device: title += ' on device {device}'.format(device=device) if interface: title += ' on interface {interf}'.format(interf=interface) if ip: title += ' for IP {ip}'.format(ip=ip) if mac: title += ' for MAC {mac}'.format(mac=mac) if device: all_arp = {device: all_arp.get(device)} for device, device_arp in six.iteritems(all_arp): if not device_arp: continue if not device_arp.get('result', False): continue arp_table = device_arp.get('out', []) for arp_entry in arp_table: if ((mac and arp_entry.get('mac', '').lower() == mac.lower()) or # pylint: disable=too-many-boolean-expressions (interface and interface in arp_entry.get('interface', '')) or (ip and napalm_helpers.convert(napalm_helpers.ip, arp_entry.get('ip', '')) == napalm_helpers.convert(napalm_helpers.ip, ip))): rows.append({ 'device': device, 'interface': arp_entry.get('interface'), 'mac': napalm_helpers.convert(napalm_helpers.mac, arp_entry.get('mac')), 'ip': napalm_helpers.convert(napalm_helpers.ip, arp_entry.get('ip')), 'age': arp_entry.get('age') }) return _display_runner(rows, labels, title, display=display)
[ "def", "findarp", "(", "device", "=", "None", ",", "interface", "=", "None", ",", "mac", "=", "None", ",", "ip", "=", "None", ",", "display", "=", "_DEFAULT_DISPLAY", ")", ":", "# pylint: disable=invalid-name", "labels", "=", "{", "'device'", ":", "'Device...
Search for entries in the ARP tables using the following mine functions: - net.arp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. mac Search using a specific MAC Address. ip Search using a specific IP Address. display: ``True`` Display on the screen or return structured object? Default: ``True``, will return on the CLI. CLI Example: .. code-block:: bash $ sudo salt-run net.findarp mac=8C:60:0F:78:EC:41 Output Example: .. code-block:: text ARP Entries for MAC 8C:60:0F:78:EC:41 ________________________________________________________________________________ | Device | Interface | MAC | IP | Age | ________________________________________________________________________________ | edge01.bjm01 | irb.171 [ae0.171] | 8C:60:0F:78:EC:41 | 172.172.17.19 | 956.0 | ________________________________________________________________________________
[ "Search", "for", "entries", "in", "the", "ARP", "tables", "using", "the", "following", "mine", "functions", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L434-L521
train
saltstack/salt
salt/runners/net.py
findmac
def findmac(device=None, mac=None, interface=None, vlan=None, display=_DEFAULT_DISPLAY): ''' Search in the MAC Address tables, using the following mine functions: - net.mac Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. mac Search using a specific MAC Address. vlan Search using a VLAN ID. display: ``True`` Display on the screen or return structured object? Default: ``True``, will return on the CLI. CLI Example: .. code-block:: bash $ sudo salt-run net.findmac mac=8C:60:0F:78:EC:41 Output Example: .. code-block:: text MAC Address(es) _____________________________________________________________________________________________ | Device | Interface | MAC | VLAN | Static | Active | Moves | Last move | _____________________________________________________________________________________________ | edge01.bjm01 | ae0.171 | 8C:60:0F:78:EC:41 | 171 | False | True | 0 | 0.0 | _____________________________________________________________________________________________ ''' labels = { 'device': 'Device', 'interface': 'Interface', 'mac': 'MAC', 'vlan': 'VLAN', 'static': 'Static', 'active': 'Active', 'moves': 'Moves', 'last_move': 'Last Move' } rows = [] all_mac = _get_mine('net.mac') title = "MAC Address(es)" if device: title += ' on device {device}'.format(device=device) if interface: title += ' on interface {interf}'.format(interf=interface) if vlan: title += ' on VLAN {vlan}'.format(vlan=vlan) if device: all_mac = {device: all_mac.get(device)} for device, device_mac in six.iteritems(all_mac): if not device_mac: continue if not device_mac.get('result', False): continue mac_table = device_mac.get('out', []) for mac_entry in mac_table: if ((mac and # pylint: disable=too-many-boolean-expressions napalm_helpers.convert(napalm_helpers.mac, mac_entry.get('mac', '')) == napalm_helpers.convert(napalm_helpers.mac, mac)) or (interface and interface in mac_entry.get('interface', '')) or (vlan and six.text_type(mac_entry.get('vlan', '')) == six.text_type(vlan))): rows.append({ 'device': device, 'interface': mac_entry.get('interface'), 'mac': napalm_helpers.convert(napalm_helpers.mac, mac_entry.get('mac')), 'vlan': mac_entry.get('vlan'), 'static': mac_entry.get('static'), 'active': mac_entry.get('active'), 'moves': mac_entry.get('moves'), 'last_move': mac_entry.get('last_move') }) return _display_runner(rows, labels, title, display=display)
python
def findmac(device=None, mac=None, interface=None, vlan=None, display=_DEFAULT_DISPLAY): ''' Search in the MAC Address tables, using the following mine functions: - net.mac Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. mac Search using a specific MAC Address. vlan Search using a VLAN ID. display: ``True`` Display on the screen or return structured object? Default: ``True``, will return on the CLI. CLI Example: .. code-block:: bash $ sudo salt-run net.findmac mac=8C:60:0F:78:EC:41 Output Example: .. code-block:: text MAC Address(es) _____________________________________________________________________________________________ | Device | Interface | MAC | VLAN | Static | Active | Moves | Last move | _____________________________________________________________________________________________ | edge01.bjm01 | ae0.171 | 8C:60:0F:78:EC:41 | 171 | False | True | 0 | 0.0 | _____________________________________________________________________________________________ ''' labels = { 'device': 'Device', 'interface': 'Interface', 'mac': 'MAC', 'vlan': 'VLAN', 'static': 'Static', 'active': 'Active', 'moves': 'Moves', 'last_move': 'Last Move' } rows = [] all_mac = _get_mine('net.mac') title = "MAC Address(es)" if device: title += ' on device {device}'.format(device=device) if interface: title += ' on interface {interf}'.format(interf=interface) if vlan: title += ' on VLAN {vlan}'.format(vlan=vlan) if device: all_mac = {device: all_mac.get(device)} for device, device_mac in six.iteritems(all_mac): if not device_mac: continue if not device_mac.get('result', False): continue mac_table = device_mac.get('out', []) for mac_entry in mac_table: if ((mac and # pylint: disable=too-many-boolean-expressions napalm_helpers.convert(napalm_helpers.mac, mac_entry.get('mac', '')) == napalm_helpers.convert(napalm_helpers.mac, mac)) or (interface and interface in mac_entry.get('interface', '')) or (vlan and six.text_type(mac_entry.get('vlan', '')) == six.text_type(vlan))): rows.append({ 'device': device, 'interface': mac_entry.get('interface'), 'mac': napalm_helpers.convert(napalm_helpers.mac, mac_entry.get('mac')), 'vlan': mac_entry.get('vlan'), 'static': mac_entry.get('static'), 'active': mac_entry.get('active'), 'moves': mac_entry.get('moves'), 'last_move': mac_entry.get('last_move') }) return _display_runner(rows, labels, title, display=display)
[ "def", "findmac", "(", "device", "=", "None", ",", "mac", "=", "None", ",", "interface", "=", "None", ",", "vlan", "=", "None", ",", "display", "=", "_DEFAULT_DISPLAY", ")", ":", "labels", "=", "{", "'device'", ":", "'Device'", ",", "'interface'", ":",...
Search in the MAC Address tables, using the following mine functions: - net.mac Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. mac Search using a specific MAC Address. vlan Search using a VLAN ID. display: ``True`` Display on the screen or return structured object? Default: ``True``, will return on the CLI. CLI Example: .. code-block:: bash $ sudo salt-run net.findmac mac=8C:60:0F:78:EC:41 Output Example: .. code-block:: text MAC Address(es) _____________________________________________________________________________________________ | Device | Interface | MAC | VLAN | Static | Active | Moves | Last move | _____________________________________________________________________________________________ | edge01.bjm01 | ae0.171 | 8C:60:0F:78:EC:41 | 171 | False | True | 0 | 0.0 | _____________________________________________________________________________________________
[ "Search", "in", "the", "MAC", "Address", "tables", "using", "the", "following", "mine", "functions", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L524-L612
train
saltstack/salt
salt/runners/net.py
lldp
def lldp(device=None, interface=None, title=None, pattern=None, chassis=None, display=_DEFAULT_DISPLAY): ''' Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return LLDP neighbors that have contain this pattern in one of the following fields: - Remote Port ID - Remote Port Description - Remote System Name - Remote System Description chassis Search using a specific Chassis ID. display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). title Display a custom title for the table. CLI Example: .. code-block:: bash $ sudo salt-run net.lldp pattern=Ethernet1/48 Output Example: .. code-block:: text Pattern "Ethernet1/48" found in one of the following LLDP details _________________________________________________________________________________________________________________________________________________________________________________________ | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port ID | Remote Port Description | Remote System Name | Remote System Description | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.bjm01 | xe-2/3/4 | ae0 | 8C:60:4F:3B:52:19 | | Ethernet1/48 | edge05.bjm01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.flw01 | xe-1/2/3 | ae0 | 8C:60:4F:1A:B4:22 | | Ethernet1/48 | edge05.flw01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.oua01 | xe-0/1/2 | ae1 | 8C:60:4F:51:A4:22 | | Ethernet1/48 | edge05.oua01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ ''' all_lldp = _get_mine('net.lldp') labels = { 'device': 'Device', 'interface': 'Interface', 'parent_interface': 'Parent Interface', 'remote_chassis_id': 'Remote Chassis ID', 'remote_port_id': 'Remote Port ID', 'remote_port_desc': 'Remote Port Description', 'remote_system_name': 'Remote System Name', 'remote_system_desc': 'Remote System Description' } rows = [] if pattern: title = 'Pattern "{0}" found in one of the following LLDP details'.format(pattern) if not title: title = 'LLDP Neighbors' if interface: title += ' for interface {0}'.format(interface) else: title += ' for all interfaces' if device: title += ' on device {0}'.format(device) if chassis: title += ' having Chassis ID {0}'.format(chassis) if device: all_lldp = {device: all_lldp.get(device)} for device, device_lldp in six.iteritems(all_lldp): if not device_lldp: continue if not device_lldp.get('result', False): continue lldp_interfaces = device_lldp.get('out', {}) if interface: lldp_interfaces = {interface: lldp_interfaces.get(interface, [])} for intrf, interface_lldp in six.iteritems(lldp_interfaces): if not interface_lldp: continue for lldp_row in interface_lldp: rsn = (lldp_row.get('remote_system_name', '') or '') rpi = (lldp_row.get('remote_port_id', '') or '') rsd = (lldp_row.get('remote_system_description', '') or '') rpd = (lldp_row.get('remote_port_description', '') or '') rci = (lldp_row.get('remote_chassis_id', '') or '') if pattern: ptl = pattern.lower() if not((ptl in rsn.lower()) or (ptl in rsd.lower()) or (ptl in rpd.lower()) or (ptl in rci.lower())): # nothing matched, let's move on continue if chassis: if (napalm_helpers.convert(napalm_helpers.mac, rci) != napalm_helpers.convert(napalm_helpers.mac, chassis)): continue rows.append({ 'device': device, 'interface': intrf, 'parent_interface': (lldp_row.get('parent_interface', '') or ''), 'remote_chassis_id': napalm_helpers.convert(napalm_helpers.mac, rci), 'remote_port_id': rpi, 'remote_port_descr': rpd, 'remote_system_name': rsn, 'remote_system_descr': rsd }) return _display_runner(rows, labels, title, display=display)
python
def lldp(device=None, interface=None, title=None, pattern=None, chassis=None, display=_DEFAULT_DISPLAY): ''' Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return LLDP neighbors that have contain this pattern in one of the following fields: - Remote Port ID - Remote Port Description - Remote System Name - Remote System Description chassis Search using a specific Chassis ID. display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). title Display a custom title for the table. CLI Example: .. code-block:: bash $ sudo salt-run net.lldp pattern=Ethernet1/48 Output Example: .. code-block:: text Pattern "Ethernet1/48" found in one of the following LLDP details _________________________________________________________________________________________________________________________________________________________________________________________ | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port ID | Remote Port Description | Remote System Name | Remote System Description | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.bjm01 | xe-2/3/4 | ae0 | 8C:60:4F:3B:52:19 | | Ethernet1/48 | edge05.bjm01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.flw01 | xe-1/2/3 | ae0 | 8C:60:4F:1A:B4:22 | | Ethernet1/48 | edge05.flw01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.oua01 | xe-0/1/2 | ae1 | 8C:60:4F:51:A4:22 | | Ethernet1/48 | edge05.oua01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ ''' all_lldp = _get_mine('net.lldp') labels = { 'device': 'Device', 'interface': 'Interface', 'parent_interface': 'Parent Interface', 'remote_chassis_id': 'Remote Chassis ID', 'remote_port_id': 'Remote Port ID', 'remote_port_desc': 'Remote Port Description', 'remote_system_name': 'Remote System Name', 'remote_system_desc': 'Remote System Description' } rows = [] if pattern: title = 'Pattern "{0}" found in one of the following LLDP details'.format(pattern) if not title: title = 'LLDP Neighbors' if interface: title += ' for interface {0}'.format(interface) else: title += ' for all interfaces' if device: title += ' on device {0}'.format(device) if chassis: title += ' having Chassis ID {0}'.format(chassis) if device: all_lldp = {device: all_lldp.get(device)} for device, device_lldp in six.iteritems(all_lldp): if not device_lldp: continue if not device_lldp.get('result', False): continue lldp_interfaces = device_lldp.get('out', {}) if interface: lldp_interfaces = {interface: lldp_interfaces.get(interface, [])} for intrf, interface_lldp in six.iteritems(lldp_interfaces): if not interface_lldp: continue for lldp_row in interface_lldp: rsn = (lldp_row.get('remote_system_name', '') or '') rpi = (lldp_row.get('remote_port_id', '') or '') rsd = (lldp_row.get('remote_system_description', '') or '') rpd = (lldp_row.get('remote_port_description', '') or '') rci = (lldp_row.get('remote_chassis_id', '') or '') if pattern: ptl = pattern.lower() if not((ptl in rsn.lower()) or (ptl in rsd.lower()) or (ptl in rpd.lower()) or (ptl in rci.lower())): # nothing matched, let's move on continue if chassis: if (napalm_helpers.convert(napalm_helpers.mac, rci) != napalm_helpers.convert(napalm_helpers.mac, chassis)): continue rows.append({ 'device': device, 'interface': intrf, 'parent_interface': (lldp_row.get('parent_interface', '') or ''), 'remote_chassis_id': napalm_helpers.convert(napalm_helpers.mac, rci), 'remote_port_id': rpi, 'remote_port_descr': rpd, 'remote_system_name': rsn, 'remote_system_descr': rsd }) return _display_runner(rows, labels, title, display=display)
[ "def", "lldp", "(", "device", "=", "None", ",", "interface", "=", "None", ",", "title", "=", "None", ",", "pattern", "=", "None", ",", "chassis", "=", "None", ",", "display", "=", "_DEFAULT_DISPLAY", ")", ":", "all_lldp", "=", "_get_mine", "(", "'net.l...
Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return LLDP neighbors that have contain this pattern in one of the following fields: - Remote Port ID - Remote Port Description - Remote System Name - Remote System Description chassis Search using a specific Chassis ID. display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). title Display a custom title for the table. CLI Example: .. code-block:: bash $ sudo salt-run net.lldp pattern=Ethernet1/48 Output Example: .. code-block:: text Pattern "Ethernet1/48" found in one of the following LLDP details _________________________________________________________________________________________________________________________________________________________________________________________ | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port ID | Remote Port Description | Remote System Name | Remote System Description | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.bjm01 | xe-2/3/4 | ae0 | 8C:60:4F:3B:52:19 | | Ethernet1/48 | edge05.bjm01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.flw01 | xe-1/2/3 | ae0 | 8C:60:4F:1A:B4:22 | | Ethernet1/48 | edge05.flw01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.oua01 | xe-0/1/2 | ae1 | 8C:60:4F:51:A4:22 | | Ethernet1/48 | edge05.oua01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________
[ "Search", "in", "the", "LLDP", "neighbors", "using", "the", "following", "mine", "functions", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L615-L752
train
saltstack/salt
salt/runners/net.py
find
def find(addr, best=True, display=_DEFAULT_DISPLAY): ''' Search in all possible entities (Interfaces, MAC tables, ARP tables, LLDP neighbors), using the following mine functions: - net.mac - net.arp - net.lldp - net.ipaddrs - net.interfaces This function has the advantage that it knows where to look, but the output might become quite long as returns all possible matches. Optional arguments: best: ``True`` Return only the best match with the interfaces IP networks when the saerching pattern is a valid IP Address or Network. display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). CLI Example: .. code-block:: bash $ sudo salt-run net.find 10.10.10.7 Output Example: .. code-block:: text Details for all interfaces that include network 10.10.10.7/32 - only best match returned ________________________________________________________________________________________________________________________ | Device | Interface | Interface Description | UP | Enabled | Speed [Mbps] | MAC Address | IP Addresses | ________________________________________________________________________________________________________________________ | edge01.flw01 | irb | | True | True | -1 | 5C:5E:AB:AC:52:B4 | 10.10.10.1/22 | ________________________________________________________________________________________________________________________ ARP Entries for IP 10.10.10.7 _____________________________________________________________________________ | Device | Interface | MAC | IP | Age | _____________________________________________________________________________ | edge01.flw01 | irb.349 [ae0.349] | 2C:60:0C:2A:4C:0A | 10.10.10.7 | 832.0 | _____________________________________________________________________________ ''' if not addr: if display: print('Please type a valid MAC/IP Address / Device / Interface / VLAN') return {} device = '' interface = '' mac = '' ip = '' # pylint: disable=invalid-name ipnet = None results = { 'int_net': [], 'int_descr': [], 'int_name': [], 'int_ip': [], 'int_mac': [], 'int_device': [], 'lldp_descr': [], 'lldp_int': [], 'lldp_device': [], 'lldp_mac': [], 'lldp_device_int': [], 'mac_device': [], 'mac_int': [], 'arp_device': [], 'arp_int': [], 'arp_mac': [], 'arp_ip': [] } if isinstance(addr, int): results['mac'] = findmac(vlan=addr, display=display) if not display: return results else: return None try: mac = napalm_helpers.convert(napalm_helpers.mac, addr) except IndexError: # no problem, let's keep searching pass if salt.utils.network.is_ipv6(addr): mac = False if not mac: try: ip = napalm_helpers.convert(napalm_helpers.ip, addr) # pylint: disable=invalid-name except ValueError: pass ipnet = _get_network_obj(addr) if ipnet: results['int_net'] = interfaces(ipnet=ipnet, best=best, display=display) if not (ipnet or ip): # search in all possible places # display all interfaces details results['int_descr'] = interfaces(pattern=addr, display=display) results['int_name'] = interfaces(interface=addr, display=display) results['int_device'] = interfaces(device=addr, display=display) # search in LLDP details results['lldp_descr'] = lldp(pattern=addr, display=display) results['lldp_int'] = lldp(interface=addr, display=display) results['lldp_device'] = lldp(device=addr, display=display) # search in MAC Address tables results['mac_device'] = findmac(device=addr, display=display) results['mac_int'] = findmac(interface=addr, display=display) # search in ARP tables results['arp_device'] = findarp(device=addr, display=display) results['arp_int'] = findarp(interface=addr, display=display) if not display: return results if mac: results['int_descr'] = findmac(mac=mac, display=display) results['arp_mac'] = findarp(mac=mac, display=display) results['lldp_mac'] = lldp(chassis=mac, display=display) if ip: results['arp_ip'] = findarp(ip=ip, display=display) # let's search in Interfaces if mac: device, interface, ips = _find_interfaces_ip(mac) ip = ', '.join(ips) # pylint: disable=invalid-name if device and interface: title = 'Interface {interface} on {device} has the physical address ({mac})'.format( interface=interface, device=device, mac=mac ) results['int_mac'] = interfaces(device=device, interface=interface, title=title, display=display) elif ip: device, interface, mac = _find_interfaces_mac(ip) if device and interface: title = 'IP Address {ip} is set for interface {interface}, on {device}'.format( interface=interface, device=device, ip=ip ) results['int_ip'] = interfaces(device=device, interface=interface, title=title, display=display) if device and interface: results['lldp_device_int'] = lldp(device, interface, display=display) if not display: return results
python
def find(addr, best=True, display=_DEFAULT_DISPLAY): ''' Search in all possible entities (Interfaces, MAC tables, ARP tables, LLDP neighbors), using the following mine functions: - net.mac - net.arp - net.lldp - net.ipaddrs - net.interfaces This function has the advantage that it knows where to look, but the output might become quite long as returns all possible matches. Optional arguments: best: ``True`` Return only the best match with the interfaces IP networks when the saerching pattern is a valid IP Address or Network. display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). CLI Example: .. code-block:: bash $ sudo salt-run net.find 10.10.10.7 Output Example: .. code-block:: text Details for all interfaces that include network 10.10.10.7/32 - only best match returned ________________________________________________________________________________________________________________________ | Device | Interface | Interface Description | UP | Enabled | Speed [Mbps] | MAC Address | IP Addresses | ________________________________________________________________________________________________________________________ | edge01.flw01 | irb | | True | True | -1 | 5C:5E:AB:AC:52:B4 | 10.10.10.1/22 | ________________________________________________________________________________________________________________________ ARP Entries for IP 10.10.10.7 _____________________________________________________________________________ | Device | Interface | MAC | IP | Age | _____________________________________________________________________________ | edge01.flw01 | irb.349 [ae0.349] | 2C:60:0C:2A:4C:0A | 10.10.10.7 | 832.0 | _____________________________________________________________________________ ''' if not addr: if display: print('Please type a valid MAC/IP Address / Device / Interface / VLAN') return {} device = '' interface = '' mac = '' ip = '' # pylint: disable=invalid-name ipnet = None results = { 'int_net': [], 'int_descr': [], 'int_name': [], 'int_ip': [], 'int_mac': [], 'int_device': [], 'lldp_descr': [], 'lldp_int': [], 'lldp_device': [], 'lldp_mac': [], 'lldp_device_int': [], 'mac_device': [], 'mac_int': [], 'arp_device': [], 'arp_int': [], 'arp_mac': [], 'arp_ip': [] } if isinstance(addr, int): results['mac'] = findmac(vlan=addr, display=display) if not display: return results else: return None try: mac = napalm_helpers.convert(napalm_helpers.mac, addr) except IndexError: # no problem, let's keep searching pass if salt.utils.network.is_ipv6(addr): mac = False if not mac: try: ip = napalm_helpers.convert(napalm_helpers.ip, addr) # pylint: disable=invalid-name except ValueError: pass ipnet = _get_network_obj(addr) if ipnet: results['int_net'] = interfaces(ipnet=ipnet, best=best, display=display) if not (ipnet or ip): # search in all possible places # display all interfaces details results['int_descr'] = interfaces(pattern=addr, display=display) results['int_name'] = interfaces(interface=addr, display=display) results['int_device'] = interfaces(device=addr, display=display) # search in LLDP details results['lldp_descr'] = lldp(pattern=addr, display=display) results['lldp_int'] = lldp(interface=addr, display=display) results['lldp_device'] = lldp(device=addr, display=display) # search in MAC Address tables results['mac_device'] = findmac(device=addr, display=display) results['mac_int'] = findmac(interface=addr, display=display) # search in ARP tables results['arp_device'] = findarp(device=addr, display=display) results['arp_int'] = findarp(interface=addr, display=display) if not display: return results if mac: results['int_descr'] = findmac(mac=mac, display=display) results['arp_mac'] = findarp(mac=mac, display=display) results['lldp_mac'] = lldp(chassis=mac, display=display) if ip: results['arp_ip'] = findarp(ip=ip, display=display) # let's search in Interfaces if mac: device, interface, ips = _find_interfaces_ip(mac) ip = ', '.join(ips) # pylint: disable=invalid-name if device and interface: title = 'Interface {interface} on {device} has the physical address ({mac})'.format( interface=interface, device=device, mac=mac ) results['int_mac'] = interfaces(device=device, interface=interface, title=title, display=display) elif ip: device, interface, mac = _find_interfaces_mac(ip) if device and interface: title = 'IP Address {ip} is set for interface {interface}, on {device}'.format( interface=interface, device=device, ip=ip ) results['int_ip'] = interfaces(device=device, interface=interface, title=title, display=display) if device and interface: results['lldp_device_int'] = lldp(device, interface, display=display) if not display: return results
[ "def", "find", "(", "addr", ",", "best", "=", "True", ",", "display", "=", "_DEFAULT_DISPLAY", ")", ":", "if", "not", "addr", ":", "if", "display", ":", "print", "(", "'Please type a valid MAC/IP Address / Device / Interface / VLAN'", ")", "return", "{", "}", ...
Search in all possible entities (Interfaces, MAC tables, ARP tables, LLDP neighbors), using the following mine functions: - net.mac - net.arp - net.lldp - net.ipaddrs - net.interfaces This function has the advantage that it knows where to look, but the output might become quite long as returns all possible matches. Optional arguments: best: ``True`` Return only the best match with the interfaces IP networks when the saerching pattern is a valid IP Address or Network. display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). CLI Example: .. code-block:: bash $ sudo salt-run net.find 10.10.10.7 Output Example: .. code-block:: text Details for all interfaces that include network 10.10.10.7/32 - only best match returned ________________________________________________________________________________________________________________________ | Device | Interface | Interface Description | UP | Enabled | Speed [Mbps] | MAC Address | IP Addresses | ________________________________________________________________________________________________________________________ | edge01.flw01 | irb | | True | True | -1 | 5C:5E:AB:AC:52:B4 | 10.10.10.1/22 | ________________________________________________________________________________________________________________________ ARP Entries for IP 10.10.10.7 _____________________________________________________________________________ | Device | Interface | MAC | IP | Age | _____________________________________________________________________________ | edge01.flw01 | irb.349 [ae0.349] | 2C:60:0C:2A:4C:0A | 10.10.10.7 | 832.0 | _____________________________________________________________________________
[ "Search", "in", "all", "possible", "entities", "(", "Interfaces", "MAC", "tables", "ARP", "tables", "LLDP", "neighbors", ")", "using", "the", "following", "mine", "functions", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L755-L907
train
saltstack/salt
salt/runners/net.py
multi_find
def multi_find(*patterns, **kwargs): ''' Execute multiple search tasks. This function is based on the `find` function. Depending on the search items, some information might overlap. Optional arguments: best: ``True`` Return only the best match with the interfaces IP networks when the saerching pattern is a valid IP Address or Network. display: ``True`` Display on the screen or return structured object? Default: `True` (return on the CLI). CLI Example: .. code-block:: bash $ sudo salt-run net.multi_find Ethernet1/49 xe-0/1/2 Output Example: .. code-block:: text Pattern "Ethernet1/49" found in one of the following LLDP details ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Details for interface xe-0/1/2 ----------------------------------------------------------------------------------------------------------------------- | Device | Interface | Interface Description | IP Addresses | Enabled | UP | MAC Address | Speed [Mbps] | ----------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 sw01.oua04 | | True | True | BE:EF:DE:AD:BE:EF | 10000 | ----------------------------------------------------------------------------------------------------------------------- LLDP Neighbors for interface xe-0/1/2 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' out = {} for pattern in set(patterns): search_result = find(pattern, best=kwargs.get('best', True), display=kwargs.get('display', _DEFAULT_DISPLAY)) out[pattern] = search_result if not kwargs.get('display', _DEFAULT_DISPLAY): return out
python
def multi_find(*patterns, **kwargs): ''' Execute multiple search tasks. This function is based on the `find` function. Depending on the search items, some information might overlap. Optional arguments: best: ``True`` Return only the best match with the interfaces IP networks when the saerching pattern is a valid IP Address or Network. display: ``True`` Display on the screen or return structured object? Default: `True` (return on the CLI). CLI Example: .. code-block:: bash $ sudo salt-run net.multi_find Ethernet1/49 xe-0/1/2 Output Example: .. code-block:: text Pattern "Ethernet1/49" found in one of the following LLDP details ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Details for interface xe-0/1/2 ----------------------------------------------------------------------------------------------------------------------- | Device | Interface | Interface Description | IP Addresses | Enabled | UP | MAC Address | Speed [Mbps] | ----------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 sw01.oua04 | | True | True | BE:EF:DE:AD:BE:EF | 10000 | ----------------------------------------------------------------------------------------------------------------------- LLDP Neighbors for interface xe-0/1/2 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' out = {} for pattern in set(patterns): search_result = find(pattern, best=kwargs.get('best', True), display=kwargs.get('display', _DEFAULT_DISPLAY)) out[pattern] = search_result if not kwargs.get('display', _DEFAULT_DISPLAY): return out
[ "def", "multi_find", "(", "*", "patterns", ",", "*", "*", "kwargs", ")", ":", "out", "=", "{", "}", "for", "pattern", "in", "set", "(", "patterns", ")", ":", "search_result", "=", "find", "(", "pattern", ",", "best", "=", "kwargs", ".", "get", "(",...
Execute multiple search tasks. This function is based on the `find` function. Depending on the search items, some information might overlap. Optional arguments: best: ``True`` Return only the best match with the interfaces IP networks when the saerching pattern is a valid IP Address or Network. display: ``True`` Display on the screen or return structured object? Default: `True` (return on the CLI). CLI Example: .. code-block:: bash $ sudo salt-run net.multi_find Ethernet1/49 xe-0/1/2 Output Example: .. code-block:: text Pattern "Ethernet1/49" found in one of the following LLDP details ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Details for interface xe-0/1/2 ----------------------------------------------------------------------------------------------------------------------- | Device | Interface | Interface Description | IP Addresses | Enabled | UP | MAC Address | Speed [Mbps] | ----------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 sw01.oua04 | | True | True | BE:EF:DE:AD:BE:EF | 10000 | ----------------------------------------------------------------------------------------------------------------------- LLDP Neighbors for interface xe-0/1/2 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
[ "Execute", "multiple", "search", "tasks", ".", "This", "function", "is", "based", "on", "the", "find", "function", ".", "Depending", "on", "the", "search", "items", "some", "information", "might", "overlap", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L910-L967
train
saltstack/salt
salt/modules/augeas_cfg.py
_recurmatch
def _recurmatch(path, aug): ''' Recursive generator providing the infrastructure for augtools print behavior. This function is based on test_augeas.py from Harald Hoyer <harald@redhat.com> in the python-augeas repository ''' if path: clean_path = path.rstrip('/*') yield (clean_path, aug.get(path)) for i in aug.match(clean_path + '/*'): i = i.replace('!', '\\!') # escape some dirs for _match in _recurmatch(i, aug): yield _match
python
def _recurmatch(path, aug): ''' Recursive generator providing the infrastructure for augtools print behavior. This function is based on test_augeas.py from Harald Hoyer <harald@redhat.com> in the python-augeas repository ''' if path: clean_path = path.rstrip('/*') yield (clean_path, aug.get(path)) for i in aug.match(clean_path + '/*'): i = i.replace('!', '\\!') # escape some dirs for _match in _recurmatch(i, aug): yield _match
[ "def", "_recurmatch", "(", "path", ",", "aug", ")", ":", "if", "path", ":", "clean_path", "=", "path", ".", "rstrip", "(", "'/*'", ")", "yield", "(", "clean_path", ",", "aug", ".", "get", "(", "path", ")", ")", "for", "i", "in", "aug", ".", "matc...
Recursive generator providing the infrastructure for augtools print behavior. This function is based on test_augeas.py from Harald Hoyer <harald@redhat.com> in the python-augeas repository
[ "Recursive", "generator", "providing", "the", "infrastructure", "for", "augtools", "print", "behavior", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L75-L91
train
saltstack/salt
salt/modules/augeas_cfg.py
_lstrip_word
def _lstrip_word(word, prefix): ''' Return a copy of the string after the specified prefix was removed from the beginning of the string ''' if six.text_type(word).startswith(prefix): return six.text_type(word)[len(prefix):] return word
python
def _lstrip_word(word, prefix): ''' Return a copy of the string after the specified prefix was removed from the beginning of the string ''' if six.text_type(word).startswith(prefix): return six.text_type(word)[len(prefix):] return word
[ "def", "_lstrip_word", "(", "word", ",", "prefix", ")", ":", "if", "six", ".", "text_type", "(", "word", ")", ".", "startswith", "(", "prefix", ")", ":", "return", "six", ".", "text_type", "(", "word", ")", "[", "len", "(", "prefix", ")", ":", "]",...
Return a copy of the string after the specified prefix was removed from the beginning of the string
[ "Return", "a", "copy", "of", "the", "string", "after", "the", "specified", "prefix", "was", "removed", "from", "the", "beginning", "of", "the", "string" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L94-L102
train
saltstack/salt
salt/modules/augeas_cfg.py
_check_load_paths
def _check_load_paths(load_path): ''' Checks the validity of the load_path, returns a sanitized version with invalid paths removed. ''' if load_path is None or not isinstance(load_path, six.string_types): return None _paths = [] for _path in load_path.split(':'): if os.path.isabs(_path) and os.path.isdir(_path): _paths.append(_path) else: log.info('Invalid augeas_cfg load_path entry: %s removed', _path) if not _paths: return None return ':'.join(_paths)
python
def _check_load_paths(load_path): ''' Checks the validity of the load_path, returns a sanitized version with invalid paths removed. ''' if load_path is None or not isinstance(load_path, six.string_types): return None _paths = [] for _path in load_path.split(':'): if os.path.isabs(_path) and os.path.isdir(_path): _paths.append(_path) else: log.info('Invalid augeas_cfg load_path entry: %s removed', _path) if not _paths: return None return ':'.join(_paths)
[ "def", "_check_load_paths", "(", "load_path", ")", ":", "if", "load_path", "is", "None", "or", "not", "isinstance", "(", "load_path", ",", "six", ".", "string_types", ")", ":", "return", "None", "_paths", "=", "[", "]", "for", "_path", "in", "load_path", ...
Checks the validity of the load_path, returns a sanitized version with invalid paths removed.
[ "Checks", "the", "validity", "of", "the", "load_path", "returns", "a", "sanitized", "version", "with", "invalid", "paths", "removed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L105-L124
train
saltstack/salt
salt/modules/augeas_cfg.py
execute
def execute(context=None, lens=None, commands=(), load_path=None): ''' Execute Augeas commands .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' augeas.execute /files/etc/redis/redis.conf \\ commands='["set bind 0.0.0.0", "set maxmemory 1G"]' context The Augeas context lens The Augeas lens to use commands The Augeas commands to execute .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' ret = {'retval': False} arg_map = { 'set': (1, 2), 'setm': (2, 3), 'move': (2,), 'insert': (3,), 'remove': (1,), } def make_path(path): ''' Return correct path ''' if not context: return path if path.lstrip('/'): if path.startswith(context): return path path = path.lstrip('/') return os.path.join(context, path) else: return context load_path = _check_load_paths(load_path) flags = _Augeas.NO_MODL_AUTOLOAD if lens and context else _Augeas.NONE aug = _Augeas(flags=flags, loadpath=load_path) if lens and context: aug.add_transform(lens, re.sub('^/files', '', context)) aug.load() for command in commands: try: # first part up to space is always the # command name (i.e.: set, move) cmd, arg = command.split(' ', 1) if cmd not in METHOD_MAP: ret['error'] = 'Command {0} is not supported (yet)'.format(cmd) return ret method = METHOD_MAP[cmd] nargs = arg_map[method] parts = salt.utils.args.shlex_split(arg) if len(parts) not in nargs: err = '{0} takes {1} args: {2}'.format(method, nargs, parts) raise ValueError(err) if method == 'set': path = make_path(parts[0]) value = parts[1] if len(parts) == 2 else None args = {'path': path, 'value': value} elif method == 'setm': base = make_path(parts[0]) sub = parts[1] value = parts[2] if len(parts) == 3 else None args = {'base': base, 'sub': sub, 'value': value} elif method == 'move': path = make_path(parts[0]) dst = parts[1] args = {'src': path, 'dst': dst} elif method == 'insert': label, where, path = parts if where not in ('before', 'after'): raise ValueError( 'Expected "before" or "after", not {0}'.format(where)) path = make_path(path) args = { 'path': path, 'label': label, 'before': where == 'before'} elif method == 'remove': path = make_path(parts[0]) args = {'path': path} except ValueError as err: log.error(err) # if command.split fails arg will not be set if 'arg' not in locals(): arg = command ret['error'] = 'Invalid formatted command, ' \ 'see debug log for details: {0}'.format(arg) return ret args = salt.utils.data.decode(args, to_str=True) log.debug('%s: %s', method, args) func = getattr(aug, method) func(**args) try: aug.save() ret['retval'] = True except IOError as err: ret['error'] = six.text_type(err) if lens and not lens.endswith('.lns'): ret['error'] += '\nLenses are normally configured as "name.lns". ' \ 'Did you mean "{0}.lns"?'.format(lens) aug.close() return ret
python
def execute(context=None, lens=None, commands=(), load_path=None): ''' Execute Augeas commands .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' augeas.execute /files/etc/redis/redis.conf \\ commands='["set bind 0.0.0.0", "set maxmemory 1G"]' context The Augeas context lens The Augeas lens to use commands The Augeas commands to execute .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' ret = {'retval': False} arg_map = { 'set': (1, 2), 'setm': (2, 3), 'move': (2,), 'insert': (3,), 'remove': (1,), } def make_path(path): ''' Return correct path ''' if not context: return path if path.lstrip('/'): if path.startswith(context): return path path = path.lstrip('/') return os.path.join(context, path) else: return context load_path = _check_load_paths(load_path) flags = _Augeas.NO_MODL_AUTOLOAD if lens and context else _Augeas.NONE aug = _Augeas(flags=flags, loadpath=load_path) if lens and context: aug.add_transform(lens, re.sub('^/files', '', context)) aug.load() for command in commands: try: # first part up to space is always the # command name (i.e.: set, move) cmd, arg = command.split(' ', 1) if cmd not in METHOD_MAP: ret['error'] = 'Command {0} is not supported (yet)'.format(cmd) return ret method = METHOD_MAP[cmd] nargs = arg_map[method] parts = salt.utils.args.shlex_split(arg) if len(parts) not in nargs: err = '{0} takes {1} args: {2}'.format(method, nargs, parts) raise ValueError(err) if method == 'set': path = make_path(parts[0]) value = parts[1] if len(parts) == 2 else None args = {'path': path, 'value': value} elif method == 'setm': base = make_path(parts[0]) sub = parts[1] value = parts[2] if len(parts) == 3 else None args = {'base': base, 'sub': sub, 'value': value} elif method == 'move': path = make_path(parts[0]) dst = parts[1] args = {'src': path, 'dst': dst} elif method == 'insert': label, where, path = parts if where not in ('before', 'after'): raise ValueError( 'Expected "before" or "after", not {0}'.format(where)) path = make_path(path) args = { 'path': path, 'label': label, 'before': where == 'before'} elif method == 'remove': path = make_path(parts[0]) args = {'path': path} except ValueError as err: log.error(err) # if command.split fails arg will not be set if 'arg' not in locals(): arg = command ret['error'] = 'Invalid formatted command, ' \ 'see debug log for details: {0}'.format(arg) return ret args = salt.utils.data.decode(args, to_str=True) log.debug('%s: %s', method, args) func = getattr(aug, method) func(**args) try: aug.save() ret['retval'] = True except IOError as err: ret['error'] = six.text_type(err) if lens and not lens.endswith('.lns'): ret['error'] += '\nLenses are normally configured as "name.lns". ' \ 'Did you mean "{0}.lns"?'.format(lens) aug.close() return ret
[ "def", "execute", "(", "context", "=", "None", ",", "lens", "=", "None", ",", "commands", "=", "(", ")", ",", "load_path", "=", "None", ")", ":", "ret", "=", "{", "'retval'", ":", "False", "}", "arg_map", "=", "{", "'set'", ":", "(", "1", ",", ...
Execute Augeas commands .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' augeas.execute /files/etc/redis/redis.conf \\ commands='["set bind 0.0.0.0", "set maxmemory 1G"]' context The Augeas context lens The Augeas lens to use commands The Augeas commands to execute .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB.
[ "Execute", "Augeas", "commands" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L127-L261
train
saltstack/salt
salt/modules/augeas_cfg.py
get
def get(path, value='', load_path=None): ''' Get a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.get /files/etc/hosts/1/ ipaddr path The path to get the value of value The optional value to get .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) ret = {} path = path.rstrip('/') if value: path += '/{0}'.format(value.strip('/')) try: _match = aug.match(path) except RuntimeError as err: return {'error': six.text_type(err)} if _match: ret[path] = aug.get(path) else: ret[path] = '' # node does not exist return ret
python
def get(path, value='', load_path=None): ''' Get a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.get /files/etc/hosts/1/ ipaddr path The path to get the value of value The optional value to get .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) ret = {} path = path.rstrip('/') if value: path += '/{0}'.format(value.strip('/')) try: _match = aug.match(path) except RuntimeError as err: return {'error': six.text_type(err)} if _match: ret[path] = aug.get(path) else: ret[path] = '' # node does not exist return ret
[ "def", "get", "(", "path", ",", "value", "=", "''", ",", "load_path", "=", "None", ")", ":", "load_path", "=", "_check_load_paths", "(", "load_path", ")", "aug", "=", "_Augeas", "(", "loadpath", "=", "load_path", ")", "ret", "=", "{", "}", "path", "=...
Get a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.get /files/etc/hosts/1/ ipaddr path The path to get the value of value The optional value to get .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB.
[ "Get", "a", "value", "for", "a", "specific", "augeas", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L264-L306
train
saltstack/salt
salt/modules/augeas_cfg.py
setvalue
def setvalue(*args): ''' Set a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost This will set the first entry in /etc/hosts to localhost CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/01/ipaddr 192.168.1.1 \\ /files/etc/hosts/01/canonical test Adds a new host to /etc/hosts the ip address 192.168.1.1 and hostname test CLI Example: .. code-block:: bash salt '*' augeas.setvalue prefix=/files/etc/sudoers/ \\ "spec[user = '%wheel']/user" "%wheel" \\ "spec[user = '%wheel']/host_group/host" 'ALL' \\ "spec[user = '%wheel']/host_group/command[1]" 'ALL' \\ "spec[user = '%wheel']/host_group/command[1]/tag" 'PASSWD' \\ "spec[user = '%wheel']/host_group/command[2]" '/usr/bin/apt-get' \\ "spec[user = '%wheel']/host_group/command[2]/tag" NOPASSWD Ensures that the following line is present in /etc/sudoers:: %wheel ALL = PASSWD : ALL , NOPASSWD : /usr/bin/apt-get , /usr/bin/aptitude ''' load_path = None load_paths = [x for x in args if six.text_type(x).startswith('load_path=')] if load_paths: if len(load_paths) > 1: raise SaltInvocationError( 'Only one \'load_path=\' value is permitted' ) else: load_path = load_paths[0].split('=', 1)[1] load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) ret = {'retval': False} tuples = [ x for x in args if not six.text_type(x).startswith('prefix=') and not six.text_type(x).startswith('load_path=')] prefix = [x for x in args if six.text_type(x).startswith('prefix=')] if prefix: if len(prefix) > 1: raise SaltInvocationError( 'Only one \'prefix=\' value is permitted' ) else: prefix = prefix[0].split('=', 1)[1] if len(tuples) % 2 != 0: raise SaltInvocationError('Uneven number of path/value arguments') tuple_iter = iter(tuples) for path, value in zip(tuple_iter, tuple_iter): target_path = path if prefix: target_path = os.path.join(prefix.rstrip('/'), path.lstrip('/')) try: aug.set(target_path, six.text_type(value)) except ValueError as err: ret['error'] = 'Multiple values: {0}'.format(err) try: aug.save() ret['retval'] = True except IOError as err: ret['error'] = six.text_type(err) return ret
python
def setvalue(*args): ''' Set a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost This will set the first entry in /etc/hosts to localhost CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/01/ipaddr 192.168.1.1 \\ /files/etc/hosts/01/canonical test Adds a new host to /etc/hosts the ip address 192.168.1.1 and hostname test CLI Example: .. code-block:: bash salt '*' augeas.setvalue prefix=/files/etc/sudoers/ \\ "spec[user = '%wheel']/user" "%wheel" \\ "spec[user = '%wheel']/host_group/host" 'ALL' \\ "spec[user = '%wheel']/host_group/command[1]" 'ALL' \\ "spec[user = '%wheel']/host_group/command[1]/tag" 'PASSWD' \\ "spec[user = '%wheel']/host_group/command[2]" '/usr/bin/apt-get' \\ "spec[user = '%wheel']/host_group/command[2]/tag" NOPASSWD Ensures that the following line is present in /etc/sudoers:: %wheel ALL = PASSWD : ALL , NOPASSWD : /usr/bin/apt-get , /usr/bin/aptitude ''' load_path = None load_paths = [x for x in args if six.text_type(x).startswith('load_path=')] if load_paths: if len(load_paths) > 1: raise SaltInvocationError( 'Only one \'load_path=\' value is permitted' ) else: load_path = load_paths[0].split('=', 1)[1] load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) ret = {'retval': False} tuples = [ x for x in args if not six.text_type(x).startswith('prefix=') and not six.text_type(x).startswith('load_path=')] prefix = [x for x in args if six.text_type(x).startswith('prefix=')] if prefix: if len(prefix) > 1: raise SaltInvocationError( 'Only one \'prefix=\' value is permitted' ) else: prefix = prefix[0].split('=', 1)[1] if len(tuples) % 2 != 0: raise SaltInvocationError('Uneven number of path/value arguments') tuple_iter = iter(tuples) for path, value in zip(tuple_iter, tuple_iter): target_path = path if prefix: target_path = os.path.join(prefix.rstrip('/'), path.lstrip('/')) try: aug.set(target_path, six.text_type(value)) except ValueError as err: ret['error'] = 'Multiple values: {0}'.format(err) try: aug.save() ret['retval'] = True except IOError as err: ret['error'] = six.text_type(err) return ret
[ "def", "setvalue", "(", "*", "args", ")", ":", "load_path", "=", "None", "load_paths", "=", "[", "x", "for", "x", "in", "args", "if", "six", ".", "text_type", "(", "x", ")", ".", "startswith", "(", "'load_path='", ")", "]", "if", "load_paths", ":", ...
Set a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost This will set the first entry in /etc/hosts to localhost CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/01/ipaddr 192.168.1.1 \\ /files/etc/hosts/01/canonical test Adds a new host to /etc/hosts the ip address 192.168.1.1 and hostname test CLI Example: .. code-block:: bash salt '*' augeas.setvalue prefix=/files/etc/sudoers/ \\ "spec[user = '%wheel']/user" "%wheel" \\ "spec[user = '%wheel']/host_group/host" 'ALL' \\ "spec[user = '%wheel']/host_group/command[1]" 'ALL' \\ "spec[user = '%wheel']/host_group/command[1]/tag" 'PASSWD' \\ "spec[user = '%wheel']/host_group/command[2]" '/usr/bin/apt-get' \\ "spec[user = '%wheel']/host_group/command[2]/tag" NOPASSWD Ensures that the following line is present in /etc/sudoers:: %wheel ALL = PASSWD : ALL , NOPASSWD : /usr/bin/apt-get , /usr/bin/aptitude
[ "Set", "a", "value", "for", "a", "specific", "augeas", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L309-L391
train
saltstack/salt
salt/modules/augeas_cfg.py
match
def match(path, value='', load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.match /files/etc/services/service-name ssh path The path to match value The value to match on .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) ret = {} try: matches = aug.match(path) except RuntimeError: return ret for _match in matches: if value and aug.get(_match) == value: ret[_match] = value elif not value: ret[_match] = aug.get(_match) return ret
python
def match(path, value='', load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.match /files/etc/services/service-name ssh path The path to match value The value to match on .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) ret = {} try: matches = aug.match(path) except RuntimeError: return ret for _match in matches: if value and aug.get(_match) == value: ret[_match] = value elif not value: ret[_match] = aug.get(_match) return ret
[ "def", "match", "(", "path", ",", "value", "=", "''", ",", "load_path", "=", "None", ")", ":", "load_path", "=", "_check_load_paths", "(", "load_path", ")", "aug", "=", "_Augeas", "(", "loadpath", "=", "load_path", ")", "ret", "=", "{", "}", "try", "...
Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.match /files/etc/services/service-name ssh path The path to match value The value to match on .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB.
[ "Get", "matches", "for", "path", "expression" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L394-L432
train
saltstack/salt
salt/modules/augeas_cfg.py
remove
def remove(path, load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.remove \\ /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians path The path to remove .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) ret = {'retval': False} try: count = aug.remove(path) aug.save() if count == -1: ret['error'] = 'Invalid node' else: ret['retval'] = True except (RuntimeError, IOError) as err: ret['error'] = six.text_type(err) ret['count'] = count return ret
python
def remove(path, load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.remove \\ /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians path The path to remove .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) ret = {'retval': False} try: count = aug.remove(path) aug.save() if count == -1: ret['error'] = 'Invalid node' else: ret['retval'] = True except (RuntimeError, IOError) as err: ret['error'] = six.text_type(err) ret['count'] = count return ret
[ "def", "remove", "(", "path", ",", "load_path", "=", "None", ")", ":", "load_path", "=", "_check_load_paths", "(", "load_path", ")", "aug", "=", "_Augeas", "(", "loadpath", "=", "load_path", ")", "ret", "=", "{", "'retval'", ":", "False", "}", "try", "...
Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.remove \\ /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians path The path to remove .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB.
[ "Get", "matches", "for", "path", "expression" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L435-L472
train
saltstack/salt
salt/modules/augeas_cfg.py
ls
def ls(path, load_path=None): # pylint: disable=C0103 ''' List the direct children of a node CLI Example: .. code-block:: bash salt '*' augeas.ls /files/etc/passwd path The path to list .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' def _match(path): ''' Internal match function ''' try: matches = aug.match(salt.utils.stringutils.to_str(path)) except RuntimeError: return {} ret = {} for _ma in matches: ret[_ma] = aug.get(_ma) return ret load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) path = path.rstrip('/') + '/' match_path = path + '*' matches = _match(match_path) ret = {} for key, value in six.iteritems(matches): name = _lstrip_word(key, path) if _match(key + '/*'): ret[name + '/'] = value # has sub nodes, e.g. directory else: ret[name] = value return ret
python
def ls(path, load_path=None): # pylint: disable=C0103 ''' List the direct children of a node CLI Example: .. code-block:: bash salt '*' augeas.ls /files/etc/passwd path The path to list .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' def _match(path): ''' Internal match function ''' try: matches = aug.match(salt.utils.stringutils.to_str(path)) except RuntimeError: return {} ret = {} for _ma in matches: ret[_ma] = aug.get(_ma) return ret load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) path = path.rstrip('/') + '/' match_path = path + '*' matches = _match(match_path) ret = {} for key, value in six.iteritems(matches): name = _lstrip_word(key, path) if _match(key + '/*'): ret[name + '/'] = value # has sub nodes, e.g. directory else: ret[name] = value return ret
[ "def", "ls", "(", "path", ",", "load_path", "=", "None", ")", ":", "# pylint: disable=C0103", "def", "_match", "(", "path", ")", ":", "''' Internal match function '''", "try", ":", "matches", "=", "aug", ".", "match", "(", "salt", ".", "utils", ".", "strin...
List the direct children of a node CLI Example: .. code-block:: bash salt '*' augeas.ls /files/etc/passwd path The path to list .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB.
[ "List", "the", "direct", "children", "of", "a", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L475-L523
train
saltstack/salt
salt/modules/augeas_cfg.py
tree
def tree(path, load_path=None): ''' Returns recursively the complete tree of a node CLI Example: .. code-block:: bash salt '*' augeas.tree /files/etc/ path The base of the recursive listing .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) path = path.rstrip('/') + '/' match_path = path return dict([i for i in _recurmatch(match_path, aug)])
python
def tree(path, load_path=None): ''' Returns recursively the complete tree of a node CLI Example: .. code-block:: bash salt '*' augeas.tree /files/etc/ path The base of the recursive listing .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB. ''' load_path = _check_load_paths(load_path) aug = _Augeas(loadpath=load_path) path = path.rstrip('/') + '/' match_path = path return dict([i for i in _recurmatch(match_path, aug)])
[ "def", "tree", "(", "path", ",", "load_path", "=", "None", ")", ":", "load_path", "=", "_check_load_paths", "(", "load_path", ")", "aug", "=", "_Augeas", "(", "loadpath", "=", "load_path", ")", "path", "=", "path", ".", "rstrip", "(", "'/'", ")", "+", ...
Returns recursively the complete tree of a node CLI Example: .. code-block:: bash salt '*' augeas.tree /files/etc/ path The base of the recursive listing .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to the standard load path and the directories in AUGEAS_LENS_LIB.
[ "Returns", "recursively", "the", "complete", "tree", "of", "a", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L526-L552
train
saltstack/salt
salt/modules/kernelpkg_linux_apt.py
list_installed
def list_installed(): ''' Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed ''' pkg_re = re.compile(r'^{0}-[\d.-]+-{1}$'.format( _package_prefix(), _kernel_type())) pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True) if pkgs is None: pkgs = [] result = list(filter(pkg_re.match, pkgs)) if result is None: return [] prefix_len = len(_package_prefix()) + 1 if six.PY2: return sorted([pkg[prefix_len:] for pkg in result], cmp=_cmp_version) else: return sorted([pkg[prefix_len:] for pkg in result], key=functools.cmp_to_key(_cmp_version))
python
def list_installed(): ''' Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed ''' pkg_re = re.compile(r'^{0}-[\d.-]+-{1}$'.format( _package_prefix(), _kernel_type())) pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True) if pkgs is None: pkgs = [] result = list(filter(pkg_re.match, pkgs)) if result is None: return [] prefix_len = len(_package_prefix()) + 1 if six.PY2: return sorted([pkg[prefix_len:] for pkg in result], cmp=_cmp_version) else: return sorted([pkg[prefix_len:] for pkg in result], key=functools.cmp_to_key(_cmp_version))
[ "def", "list_installed", "(", ")", ":", "pkg_re", "=", "re", ".", "compile", "(", "r'^{0}-[\\d.-]+-{1}$'", ".", "format", "(", "_package_prefix", "(", ")", ",", "_kernel_type", "(", ")", ")", ")", "pkgs", "=", "__salt__", "[", "'pkg.list_pkgs'", "]", "(", ...
Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed
[ "Return", "a", "list", "of", "all", "installed", "kernels", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kernelpkg_linux_apt.py#L58-L83
train
saltstack/salt
salt/modules/kernelpkg_linux_apt.py
upgrade
def upgrade(reboot=False, at_time=None): ''' Upgrade the kernel and optionally reboot the system. reboot : False Request a reboot if a new kernel is available. at_time : immediate Schedule the reboot at some point in the future. This argument is ignored if ``reboot=False``. See :py:func:`~salt.modules.system.reboot` for more details on this argument. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade salt '*' kernelpkg.upgrade reboot=True at_time=1 .. note:: An immediate reboot often shuts down the system before the minion has a chance to return, resulting in errors. A minimal delay (1 minute) is useful to ensure the result is delivered to the master. ''' result = __salt__['pkg.install']( name='{0}-{1}'.format(_package_prefix(), latest_available())) _needs_reboot = needs_reboot() ret = { 'upgrades': result, 'active': active(), 'latest_installed': latest_installed(), 'reboot_requested': reboot, 'reboot_required': _needs_reboot } if reboot and _needs_reboot: log.warning('Rebooting system due to kernel upgrade') __salt__['system.reboot'](at_time=at_time) return ret
python
def upgrade(reboot=False, at_time=None): ''' Upgrade the kernel and optionally reboot the system. reboot : False Request a reboot if a new kernel is available. at_time : immediate Schedule the reboot at some point in the future. This argument is ignored if ``reboot=False``. See :py:func:`~salt.modules.system.reboot` for more details on this argument. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade salt '*' kernelpkg.upgrade reboot=True at_time=1 .. note:: An immediate reboot often shuts down the system before the minion has a chance to return, resulting in errors. A minimal delay (1 minute) is useful to ensure the result is delivered to the master. ''' result = __salt__['pkg.install']( name='{0}-{1}'.format(_package_prefix(), latest_available())) _needs_reboot = needs_reboot() ret = { 'upgrades': result, 'active': active(), 'latest_installed': latest_installed(), 'reboot_requested': reboot, 'reboot_required': _needs_reboot } if reboot and _needs_reboot: log.warning('Rebooting system due to kernel upgrade') __salt__['system.reboot'](at_time=at_time) return ret
[ "def", "upgrade", "(", "reboot", "=", "False", ",", "at_time", "=", "None", ")", ":", "result", "=", "__salt__", "[", "'pkg.install'", "]", "(", "name", "=", "'{0}-{1}'", ".", "format", "(", "_package_prefix", "(", ")", ",", "latest_available", "(", ")",...
Upgrade the kernel and optionally reboot the system. reboot : False Request a reboot if a new kernel is available. at_time : immediate Schedule the reboot at some point in the future. This argument is ignored if ``reboot=False``. See :py:func:`~salt.modules.system.reboot` for more details on this argument. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade salt '*' kernelpkg.upgrade reboot=True at_time=1 .. note:: An immediate reboot often shuts down the system before the minion has a chance to return, resulting in errors. A minimal delay (1 minute) is useful to ensure the result is delivered to the master.
[ "Upgrade", "the", "kernel", "and", "optionally", "reboot", "the", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kernelpkg_linux_apt.py#L144-L185
train
saltstack/salt
salt/modules/kernelpkg_linux_apt.py
remove
def remove(release): ''' Remove a specific version of the kernel. release The release number of an installed kernel. This must be the entire release number as returned by :py:func:`~salt.modules.kernelpkg_linux_apt.list_installed`, not the package name. CLI Example: .. code-block:: bash salt '*' kernelpkg.remove 4.4.0-70-generic ''' if release not in list_installed(): raise CommandExecutionError('Kernel release \'{0}\' is not installed'.format(release)) if release == active(): raise CommandExecutionError('Active kernel cannot be removed') target = '{0}-{1}'.format(_package_prefix(), release) log.info('Removing kernel package %s', target) __salt__['pkg.purge'](target) return {'removed': [target]}
python
def remove(release): ''' Remove a specific version of the kernel. release The release number of an installed kernel. This must be the entire release number as returned by :py:func:`~salt.modules.kernelpkg_linux_apt.list_installed`, not the package name. CLI Example: .. code-block:: bash salt '*' kernelpkg.remove 4.4.0-70-generic ''' if release not in list_installed(): raise CommandExecutionError('Kernel release \'{0}\' is not installed'.format(release)) if release == active(): raise CommandExecutionError('Active kernel cannot be removed') target = '{0}-{1}'.format(_package_prefix(), release) log.info('Removing kernel package %s', target) __salt__['pkg.purge'](target) return {'removed': [target]}
[ "def", "remove", "(", "release", ")", ":", "if", "release", "not", "in", "list_installed", "(", ")", ":", "raise", "CommandExecutionError", "(", "'Kernel release \\'{0}\\' is not installed'", ".", "format", "(", "release", ")", ")", "if", "release", "==", "activ...
Remove a specific version of the kernel. release The release number of an installed kernel. This must be the entire release number as returned by :py:func:`~salt.modules.kernelpkg_linux_apt.list_installed`, not the package name. CLI Example: .. code-block:: bash salt '*' kernelpkg.remove 4.4.0-70-generic
[ "Remove", "a", "specific", "version", "of", "the", "kernel", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kernelpkg_linux_apt.py#L202-L228
train
saltstack/salt
salt/modules/kernelpkg_linux_apt.py
cleanup
def cleanup(keep_latest=True): ''' Remove all unused kernel packages from the system. keep_latest : True In the event that the active kernel is not the latest one installed, setting this to True will retain the latest kernel package, in addition to the active one. If False, all kernel packages other than the active one will be removed. CLI Example: .. code-block:: bash salt '*' kernelpkg.cleanup ''' removed = [] # Loop over all installed kernel packages for kernel in list_installed(): # Keep the active kernel package if kernel == active(): continue # Optionally keep the latest kernel package if keep_latest and kernel == latest_installed(): continue # Remove the kernel package removed.extend(remove(kernel)['removed']) return {'removed': removed}
python
def cleanup(keep_latest=True): ''' Remove all unused kernel packages from the system. keep_latest : True In the event that the active kernel is not the latest one installed, setting this to True will retain the latest kernel package, in addition to the active one. If False, all kernel packages other than the active one will be removed. CLI Example: .. code-block:: bash salt '*' kernelpkg.cleanup ''' removed = [] # Loop over all installed kernel packages for kernel in list_installed(): # Keep the active kernel package if kernel == active(): continue # Optionally keep the latest kernel package if keep_latest and kernel == latest_installed(): continue # Remove the kernel package removed.extend(remove(kernel)['removed']) return {'removed': removed}
[ "def", "cleanup", "(", "keep_latest", "=", "True", ")", ":", "removed", "=", "[", "]", "# Loop over all installed kernel packages", "for", "kernel", "in", "list_installed", "(", ")", ":", "# Keep the active kernel package", "if", "kernel", "==", "active", "(", ")"...
Remove all unused kernel packages from the system. keep_latest : True In the event that the active kernel is not the latest one installed, setting this to True will retain the latest kernel package, in addition to the active one. If False, all kernel packages other than the active one will be removed. CLI Example: .. code-block:: bash salt '*' kernelpkg.cleanup
[ "Remove", "all", "unused", "kernel", "packages", "from", "the", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kernelpkg_linux_apt.py#L231-L262
train
saltstack/salt
salt/modules/kernelpkg_linux_apt.py
_cmp_version
def _cmp_version(item1, item2): ''' Compare function for package version sorting ''' vers1 = _LooseVersion(item1) vers2 = _LooseVersion(item2) if vers1 < vers2: return -1 if vers1 > vers2: return 1 return 0
python
def _cmp_version(item1, item2): ''' Compare function for package version sorting ''' vers1 = _LooseVersion(item1) vers2 = _LooseVersion(item2) if vers1 < vers2: return -1 if vers1 > vers2: return 1 return 0
[ "def", "_cmp_version", "(", "item1", ",", "item2", ")", ":", "vers1", "=", "_LooseVersion", "(", "item1", ")", "vers2", "=", "_LooseVersion", "(", "item2", ")", "if", "vers1", "<", "vers2", ":", "return", "-", "1", "if", "vers1", ">", "vers2", ":", "...
Compare function for package version sorting
[ "Compare", "function", "for", "package", "version", "sorting" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kernelpkg_linux_apt.py#L279-L290
train
saltstack/salt
salt/states/redismod.py
string
def string(name, value, expire=None, expireat=None, **connection_args): ''' Ensure that the key exists in redis with the value specified name Redis key to manage value Data to persist in key expire Sets time to live for key in seconds expireat Sets expiration time for key via UNIX timestamp, overrides `expire` ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Key already set to defined value'} old_key = __salt__['redis.get_key'](name, **connection_args) if old_key != value: __salt__['redis.set_key'](name, value, **connection_args) ret['changes'][name] = 'Value updated' ret['comment'] = 'Key updated to new value' if expireat: __salt__['redis.expireat'](name, expireat, **connection_args) ret['changes']['expireat'] = 'Key expires at {0}'.format(expireat) elif expire: __salt__['redis.expire'](name, expire, **connection_args) ret['changes']['expire'] = 'TTL set to {0} seconds'.format(expire) return ret
python
def string(name, value, expire=None, expireat=None, **connection_args): ''' Ensure that the key exists in redis with the value specified name Redis key to manage value Data to persist in key expire Sets time to live for key in seconds expireat Sets expiration time for key via UNIX timestamp, overrides `expire` ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Key already set to defined value'} old_key = __salt__['redis.get_key'](name, **connection_args) if old_key != value: __salt__['redis.set_key'](name, value, **connection_args) ret['changes'][name] = 'Value updated' ret['comment'] = 'Key updated to new value' if expireat: __salt__['redis.expireat'](name, expireat, **connection_args) ret['changes']['expireat'] = 'Key expires at {0}'.format(expireat) elif expire: __salt__['redis.expire'](name, expire, **connection_args) ret['changes']['expire'] = 'TTL set to {0} seconds'.format(expire) return ret
[ "def", "string", "(", "name", ",", "value", ",", "expire", "=", "None", ",", "expireat", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True",...
Ensure that the key exists in redis with the value specified name Redis key to manage value Data to persist in key expire Sets time to live for key in seconds expireat Sets expiration time for key via UNIX timestamp, overrides `expire`
[ "Ensure", "that", "the", "key", "exists", "in", "redis", "with", "the", "value", "specified" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/redismod.py#L46-L81
train
saltstack/salt
salt/states/redismod.py
absent
def absent(name, keys=None, **connection_args): ''' Ensure key absent from redis name Key to ensure absent from redis keys list of keys to ensure absent, name will be ignored if this is used ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Key(s) specified already absent'} if keys: if not isinstance(keys, list): ret['result'] = False ret['comment'] = '`keys` not formed as a list type' return ret delete_list = [key for key in keys if __salt__['redis.exists'](key, **connection_args)] if not delete_list: return ret __salt__['redis.delete'](*delete_list, **connection_args) ret['changes']['deleted'] = delete_list ret['comment'] = 'Keys deleted' return ret if __salt__['redis.exists'](name, **connection_args): __salt__['redis.delete'](name, **connection_args) ret['comment'] = 'Key deleted' ret['changes']['deleted'] = [name] return ret
python
def absent(name, keys=None, **connection_args): ''' Ensure key absent from redis name Key to ensure absent from redis keys list of keys to ensure absent, name will be ignored if this is used ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Key(s) specified already absent'} if keys: if not isinstance(keys, list): ret['result'] = False ret['comment'] = '`keys` not formed as a list type' return ret delete_list = [key for key in keys if __salt__['redis.exists'](key, **connection_args)] if not delete_list: return ret __salt__['redis.delete'](*delete_list, **connection_args) ret['changes']['deleted'] = delete_list ret['comment'] = 'Keys deleted' return ret if __salt__['redis.exists'](name, **connection_args): __salt__['redis.delete'](name, **connection_args) ret['comment'] = 'Key deleted' ret['changes']['deleted'] = [name] return ret
[ "def", "absent", "(", "name", ",", "keys", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'Key(s) specified already...
Ensure key absent from redis name Key to ensure absent from redis keys list of keys to ensure absent, name will be ignored if this is used
[ "Ensure", "key", "absent", "from", "redis" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/redismod.py#L84-L117
train
saltstack/salt
salt/states/redismod.py
slaveof
def slaveof(name, sentinel_host=None, sentinel_port=None, sentinel_password=None, **connection_args): ''' Set this redis instance as a slave. .. versionadded: 2016.3.0 name Master to make this a slave of sentinel_host Ip of the sentinel to check for the master sentinel_port Port of the sentinel to check for the master ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': 'Failed to setup slave'} kwargs = copy.copy(connection_args) sentinel_master = __salt__['redis.sentinel_get_master_ip'](name, sentinel_host, sentinel_port, sentinel_password) if sentinel_master['master_host'] in __salt__['network.ip_addrs'](): ret['result'] = True ret['comment'] = 'Minion is the master: {0}'.format(name) return ret first_master = __salt__['redis.get_master_ip'](**connection_args) if first_master == sentinel_master: ret['result'] = True ret['comment'] = 'Minion already slave of master: {0}'.format(name) return ret if __opts__['test'] is True: ret['comment'] = 'Minion will be made a slave of {0}: {1}'.format(name, sentinel_master['host']) ret['result'] = None return ret kwargs.update(**sentinel_master) __salt__['redis.slaveof'](**kwargs) current_master = __salt__['redis.get_master_ip'](**connection_args) if current_master != sentinel_master: return ret ret['result'] = True ret['changes'] = { 'old': first_master, 'new': current_master, } ret['comment'] = 'Minion successfully connected to master: {0}'.format(name) return ret
python
def slaveof(name, sentinel_host=None, sentinel_port=None, sentinel_password=None, **connection_args): ''' Set this redis instance as a slave. .. versionadded: 2016.3.0 name Master to make this a slave of sentinel_host Ip of the sentinel to check for the master sentinel_port Port of the sentinel to check for the master ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': 'Failed to setup slave'} kwargs = copy.copy(connection_args) sentinel_master = __salt__['redis.sentinel_get_master_ip'](name, sentinel_host, sentinel_port, sentinel_password) if sentinel_master['master_host'] in __salt__['network.ip_addrs'](): ret['result'] = True ret['comment'] = 'Minion is the master: {0}'.format(name) return ret first_master = __salt__['redis.get_master_ip'](**connection_args) if first_master == sentinel_master: ret['result'] = True ret['comment'] = 'Minion already slave of master: {0}'.format(name) return ret if __opts__['test'] is True: ret['comment'] = 'Minion will be made a slave of {0}: {1}'.format(name, sentinel_master['host']) ret['result'] = None return ret kwargs.update(**sentinel_master) __salt__['redis.slaveof'](**kwargs) current_master = __salt__['redis.get_master_ip'](**connection_args) if current_master != sentinel_master: return ret ret['result'] = True ret['changes'] = { 'old': first_master, 'new': current_master, } ret['comment'] = 'Minion successfully connected to master: {0}'.format(name) return ret
[ "def", "slaveof", "(", "name", ",", "sentinel_host", "=", "None", ",", "sentinel_port", "=", "None", ",", "sentinel_password", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", ...
Set this redis instance as a slave. .. versionadded: 2016.3.0 name Master to make this a slave of sentinel_host Ip of the sentinel to check for the master sentinel_port Port of the sentinel to check for the master
[ "Set", "this", "redis", "instance", "as", "a", "slave", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/redismod.py#L120-L173
train
saltstack/salt
salt/utils/pkg/win.py
__main
def __main(): '''This module can also be run directly for testing Args: detail|list : Provide ``detail`` or version ``list``. system|system+user: System installed and System and User installs. ''' if len(sys.argv) < 3: sys.stderr.write('usage: {0} <detail|list> <system|system+user>\n'.format(sys.argv[0])) sys.exit(64) user_pkgs = False version_only = False if six.text_type(sys.argv[1]) == 'list': version_only = True if six.text_type(sys.argv[2]) == 'system+user': user_pkgs = True import salt.utils.json import timeit def run(): ''' Main run code, when this module is run directly ''' pkg_list = WinSoftware(user_pkgs=user_pkgs, version_only=version_only) print(salt.utils.json.dumps(pkg_list.data, sort_keys=True, indent=4)) # pylint: disable=superfluous-parens print('Total: {}'.format(len(pkg_list))) # pylint: disable=superfluous-parens print('Time Taken: {}'.format(timeit.timeit(run, number=1)))
python
def __main(): '''This module can also be run directly for testing Args: detail|list : Provide ``detail`` or version ``list``. system|system+user: System installed and System and User installs. ''' if len(sys.argv) < 3: sys.stderr.write('usage: {0} <detail|list> <system|system+user>\n'.format(sys.argv[0])) sys.exit(64) user_pkgs = False version_only = False if six.text_type(sys.argv[1]) == 'list': version_only = True if six.text_type(sys.argv[2]) == 'system+user': user_pkgs = True import salt.utils.json import timeit def run(): ''' Main run code, when this module is run directly ''' pkg_list = WinSoftware(user_pkgs=user_pkgs, version_only=version_only) print(salt.utils.json.dumps(pkg_list.data, sort_keys=True, indent=4)) # pylint: disable=superfluous-parens print('Total: {}'.format(len(pkg_list))) # pylint: disable=superfluous-parens print('Time Taken: {}'.format(timeit.timeit(run, number=1)))
[ "def", "__main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "<", "3", ":", "sys", ".", "stderr", ".", "write", "(", "'usage: {0} <detail|list> <system|system+user>\\n'", ".", "format", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", ...
This module can also be run directly for testing Args: detail|list : Provide ``detail`` or version ``list``. system|system+user: System installed and System and User installs.
[ "This", "module", "can", "also", "be", "run", "directly", "for", "testing", "Args", ":", "detail|list", ":", "Provide", "detail", "or", "version", "list", ".", "system|system", "+", "user", ":", "System", "installed", "and", "System", "and", "User", "install...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L1295-L1321
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.__squid_to_guid
def __squid_to_guid(self, squid): ''' Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided. ''' if not squid: return '' squid_match = self.__squid_pattern.match(squid) guid = '' if squid_match is not None: guid = '{' +\ squid_match.group(1)[::-1]+'-' +\ squid_match.group(2)[::-1]+'-' +\ squid_match.group(3)[::-1]+'-' +\ squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-' for index in range(6, 12): guid += squid_match.group(index)[::-1] guid += '}' return guid
python
def __squid_to_guid(self, squid): ''' Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided. ''' if not squid: return '' squid_match = self.__squid_pattern.match(squid) guid = '' if squid_match is not None: guid = '{' +\ squid_match.group(1)[::-1]+'-' +\ squid_match.group(2)[::-1]+'-' +\ squid_match.group(3)[::-1]+'-' +\ squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-' for index in range(6, 12): guid += squid_match.group(index)[::-1] guid += '}' return guid
[ "def", "__squid_to_guid", "(", "self", ",", "squid", ")", ":", "if", "not", "squid", ":", "return", "''", "squid_match", "=", "self", ".", "__squid_pattern", ".", "match", "(", "squid", ")", "guid", "=", "''", "if", "squid_match", "is", "not", "None", ...
Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided.
[ "Squished", "GUID", "(", "SQUID", ")", "to", "GUID", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L235-L261
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.__one_equals_true
def __one_equals_true(value): ''' Test for ``1`` as a number or a string and return ``True`` if it is. Args: value: string or number or None. Returns: bool: ``True`` if 1 otherwise ``False``. ''' if isinstance(value, six.integer_types) and value == 1: return True elif (isinstance(value, six.string_types) and re.match(r'\d+', value, flags=re.IGNORECASE + re.UNICODE) is not None and six.text_type(value) == '1'): return True return False
python
def __one_equals_true(value): ''' Test for ``1`` as a number or a string and return ``True`` if it is. Args: value: string or number or None. Returns: bool: ``True`` if 1 otherwise ``False``. ''' if isinstance(value, six.integer_types) and value == 1: return True elif (isinstance(value, six.string_types) and re.match(r'\d+', value, flags=re.IGNORECASE + re.UNICODE) is not None and six.text_type(value) == '1'): return True return False
[ "def", "__one_equals_true", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "integer_types", ")", "and", "value", "==", "1", ":", "return", "True", "elif", "(", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ...
Test for ``1`` as a number or a string and return ``True`` if it is. Args: value: string or number or None. Returns: bool: ``True`` if 1 otherwise ``False``.
[ "Test", "for", "1", "as", "a", "number", "or", "a", "string", "and", "return", "True", "if", "it", "is", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L264-L280
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.__reg_query_value
def __reg_query_value(handle, value_name): ''' Calls RegQueryValueEx If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning Remember to catch not found exceptions when calling. Args: handle (object): open registry handle. value_name (str): Name of the value you wished returned Returns: tuple: type, value ''' # item_value, item_type = win32api.RegQueryValueEx(self.__reg_uninstall_handle, value_name) item_value, item_type = win32api.RegQueryValueEx(handle, value_name) # pylint: disable=no-member if six.PY2 and isinstance(item_value, six.string_types) and not isinstance(item_value, six.text_type): try: item_value = six.text_type(item_value, encoding='mbcs') except UnicodeError: pass if item_type == win32con.REG_EXPAND_SZ: # expects Unicode input win32api.ExpandEnvironmentStrings(item_value) # pylint: disable=no-member item_type = win32con.REG_SZ return item_value, item_type
python
def __reg_query_value(handle, value_name): ''' Calls RegQueryValueEx If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning Remember to catch not found exceptions when calling. Args: handle (object): open registry handle. value_name (str): Name of the value you wished returned Returns: tuple: type, value ''' # item_value, item_type = win32api.RegQueryValueEx(self.__reg_uninstall_handle, value_name) item_value, item_type = win32api.RegQueryValueEx(handle, value_name) # pylint: disable=no-member if six.PY2 and isinstance(item_value, six.string_types) and not isinstance(item_value, six.text_type): try: item_value = six.text_type(item_value, encoding='mbcs') except UnicodeError: pass if item_type == win32con.REG_EXPAND_SZ: # expects Unicode input win32api.ExpandEnvironmentStrings(item_value) # pylint: disable=no-member item_type = win32con.REG_SZ return item_value, item_type
[ "def", "__reg_query_value", "(", "handle", ",", "value_name", ")", ":", "# item_value, item_type = win32api.RegQueryValueEx(self.__reg_uninstall_handle, value_name)", "item_value", ",", "item_type", "=", "win32api", ".", "RegQueryValueEx", "(", "handle", ",", "value_name", ")...
Calls RegQueryValueEx If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning Remember to catch not found exceptions when calling. Args: handle (object): open registry handle. value_name (str): Name of the value you wished returned Returns: tuple: type, value
[ "Calls", "RegQueryValueEx" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L283-L308
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.install_time
def install_time(self): ''' Return the install time, or provide an estimate of install time. Installers or even self upgrading software must/should update the date held within InstallDate field when they change versions. Some installers do not set ``InstallDate`` at all so we use the last modified time on the registry key. Returns: int: Seconds since 1970 UTC. ''' time1970 = self.__mod_time1970 # time of last resort try: # pylint: disable=no-member date_string, item_type = \ win32api.RegQueryValueEx(self.__reg_uninstall_handle, 'InstallDate') except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: return time1970 # i.e. use time of last resort else: raise if item_type == win32con.REG_SZ: try: date_object = datetime.datetime.strptime(date_string, "%Y%m%d") time1970 = time.mktime(date_object.timetuple()) except ValueError: # date format is not correct pass return time1970
python
def install_time(self): ''' Return the install time, or provide an estimate of install time. Installers or even self upgrading software must/should update the date held within InstallDate field when they change versions. Some installers do not set ``InstallDate`` at all so we use the last modified time on the registry key. Returns: int: Seconds since 1970 UTC. ''' time1970 = self.__mod_time1970 # time of last resort try: # pylint: disable=no-member date_string, item_type = \ win32api.RegQueryValueEx(self.__reg_uninstall_handle, 'InstallDate') except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: return time1970 # i.e. use time of last resort else: raise if item_type == win32con.REG_SZ: try: date_object = datetime.datetime.strptime(date_string, "%Y%m%d") time1970 = time.mktime(date_object.timetuple()) except ValueError: # date format is not correct pass return time1970
[ "def", "install_time", "(", "self", ")", ":", "time1970", "=", "self", ".", "__mod_time1970", "# time of last resort", "try", ":", "# pylint: disable=no-member", "date_string", ",", "item_type", "=", "win32api", ".", "RegQueryValueEx", "(", "self", ".", "__reg_unins...
Return the install time, or provide an estimate of install time. Installers or even self upgrading software must/should update the date held within InstallDate field when they change versions. Some installers do not set ``InstallDate`` at all so we use the last modified time on the registry key. Returns: int: Seconds since 1970 UTC.
[ "Return", "the", "install", "time", "or", "provide", "an", "estimate", "of", "install", "time", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L311-L341
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.get_install_value
def get_install_value(self, value_name, wanted_type=None): ''' For the uninstall section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match None is return. wanted_type support values are ``str`` ``int`` ``list`` ``bytes``. Returns: value: Value requested or None if not found. ''' try: item_value, item_type = self.__reg_query_value(self.__reg_uninstall_handle, value_name) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found return None raise if wanted_type and item_type not in self.__reg_types[wanted_type]: item_value = None return item_value
python
def get_install_value(self, value_name, wanted_type=None): ''' For the uninstall section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match None is return. wanted_type support values are ``str`` ``int`` ``list`` ``bytes``. Returns: value: Value requested or None if not found. ''' try: item_value, item_type = self.__reg_query_value(self.__reg_uninstall_handle, value_name) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found return None raise if wanted_type and item_type not in self.__reg_types[wanted_type]: item_value = None return item_value
[ "def", "get_install_value", "(", "self", ",", "value_name", ",", "wanted_type", "=", "None", ")", ":", "try", ":", "item_value", ",", "item_type", "=", "self", ".", "__reg_query_value", "(", "self", ".", "__reg_uninstall_handle", ",", "value_name", ")", "excep...
For the uninstall section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match None is return. wanted_type support values are ``str`` ``int`` ``list`` ``bytes``. Returns: value: Value requested or None if not found.
[ "For", "the", "uninstall", "section", "of", "the", "registry", "return", "the", "name", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L343-L368
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.get_product_value
def get_product_value(self, value_name, wanted_type=None): ''' For the product section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match None is return. wanted_type support values are ``str`` ``int`` ``list`` ``bytes``. Returns: value: Value requested or ``None`` if not found. ''' if not self.__reg_products_handle: return None subkey, search_value_name = os.path.split(value_name) try: if subkey: handle = win32api.RegOpenKeyEx( # pylint: disable=no-member self.__reg_products_handle, subkey, 0, win32con.KEY_READ | self.__reg_32bit_access) item_value, item_type = self.__reg_query_value(handle, search_value_name) win32api.RegCloseKey(handle) # pylint: disable=no-member else: item_value, item_type = \ win32api.RegQueryValueEx(self.__reg_products_handle, value_name) # pylint: disable=no-member except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found return None raise if wanted_type and item_type not in self.__reg_types[wanted_type]: item_value = None return item_value
python
def get_product_value(self, value_name, wanted_type=None): ''' For the product section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match None is return. wanted_type support values are ``str`` ``int`` ``list`` ``bytes``. Returns: value: Value requested or ``None`` if not found. ''' if not self.__reg_products_handle: return None subkey, search_value_name = os.path.split(value_name) try: if subkey: handle = win32api.RegOpenKeyEx( # pylint: disable=no-member self.__reg_products_handle, subkey, 0, win32con.KEY_READ | self.__reg_32bit_access) item_value, item_type = self.__reg_query_value(handle, search_value_name) win32api.RegCloseKey(handle) # pylint: disable=no-member else: item_value, item_type = \ win32api.RegQueryValueEx(self.__reg_products_handle, value_name) # pylint: disable=no-member except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found return None raise if wanted_type and item_type not in self.__reg_types[wanted_type]: item_value = None return item_value
[ "def", "get_product_value", "(", "self", ",", "value_name", ",", "wanted_type", "=", "None", ")", ":", "if", "not", "self", ".", "__reg_products_handle", ":", "return", "None", "subkey", ",", "search_value_name", "=", "os", ".", "path", ".", "split", "(", ...
For the product section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match None is return. wanted_type support values are ``str`` ``int`` ``list`` ``bytes``. Returns: value: Value requested or ``None`` if not found.
[ "For", "the", "product", "section", "of", "the", "registry", "return", "the", "name", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L382-L420
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.upgrade_code
def upgrade_code(self): ''' For installers which follow the Microsoft Installer standard, returns the ``Upgrade code``. Returns: value (str): ``Upgrade code`` GUID for installed software. ''' if not self.__squid: # Must have a valid squid for an upgrade code to exist return '' # GUID/SQUID are unique, so it does not matter if they are 32bit or # 64bit or user install so all items are cached into a single dict have_scan_key = '{0}\\{1}\\{2}'.format(self.__reg_hive, self.__reg_upgradecode_path, self.__reg_32bit) if not self.__upgrade_codes or self.__reg_key_guid not in self.__upgrade_codes: # Read in the upgrade codes in this section of the registry. try: uc_handle = win32api.RegOpenKeyEx(getattr(win32con, self.__reg_hive), # pylint: disable=no-member self.__reg_upgradecode_path, 0, win32con.KEY_READ | self.__reg_32bit_access) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found log.warning( 'Not Found %s\\%s 32bit %s', self.__reg_hive, self.__reg_upgradecode_path, self.__reg_32bit ) return '' raise squid_upgrade_code_all, _, _, suc_pytime = zip(*win32api.RegEnumKeyEx(uc_handle)) # pylint: disable=no-member # Check if we have already scanned these upgrade codes before, and also # check if they have been updated in the registry since last time we scanned. if (have_scan_key in self.__upgrade_code_have_scan and self.__upgrade_code_have_scan[have_scan_key] == (squid_upgrade_code_all, suc_pytime)): log.debug('Scan skipped for upgrade codes, no changes (%s)', have_scan_key) return '' # we have scanned this before and no new changes. # Go into each squid upgrade code and find all the related product codes. log.debug('Scan for upgrade codes (%s) for product codes', have_scan_key) for upgrade_code_squid in squid_upgrade_code_all: upgrade_code_guid = self.__squid_to_guid(upgrade_code_squid) pc_handle = win32api.RegOpenKeyEx(uc_handle, # pylint: disable=no-member upgrade_code_squid, 0, win32con.KEY_READ | self.__reg_32bit_access) _, pc_val_count, _ = win32api.RegQueryInfoKey(pc_handle) # pylint: disable=no-member for item_index in range(pc_val_count): product_code_guid = \ self.__squid_to_guid(win32api.RegEnumValue(pc_handle, item_index)[0]) # pylint: disable=no-member if product_code_guid: self.__upgrade_codes[product_code_guid] = upgrade_code_guid win32api.RegCloseKey(pc_handle) # pylint: disable=no-member win32api.RegCloseKey(uc_handle) # pylint: disable=no-member self.__upgrade_code_have_scan[have_scan_key] = (squid_upgrade_code_all, suc_pytime) return self.__upgrade_codes.get(self.__reg_key_guid, '')
python
def upgrade_code(self): ''' For installers which follow the Microsoft Installer standard, returns the ``Upgrade code``. Returns: value (str): ``Upgrade code`` GUID for installed software. ''' if not self.__squid: # Must have a valid squid for an upgrade code to exist return '' # GUID/SQUID are unique, so it does not matter if they are 32bit or # 64bit or user install so all items are cached into a single dict have_scan_key = '{0}\\{1}\\{2}'.format(self.__reg_hive, self.__reg_upgradecode_path, self.__reg_32bit) if not self.__upgrade_codes or self.__reg_key_guid not in self.__upgrade_codes: # Read in the upgrade codes in this section of the registry. try: uc_handle = win32api.RegOpenKeyEx(getattr(win32con, self.__reg_hive), # pylint: disable=no-member self.__reg_upgradecode_path, 0, win32con.KEY_READ | self.__reg_32bit_access) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found log.warning( 'Not Found %s\\%s 32bit %s', self.__reg_hive, self.__reg_upgradecode_path, self.__reg_32bit ) return '' raise squid_upgrade_code_all, _, _, suc_pytime = zip(*win32api.RegEnumKeyEx(uc_handle)) # pylint: disable=no-member # Check if we have already scanned these upgrade codes before, and also # check if they have been updated in the registry since last time we scanned. if (have_scan_key in self.__upgrade_code_have_scan and self.__upgrade_code_have_scan[have_scan_key] == (squid_upgrade_code_all, suc_pytime)): log.debug('Scan skipped for upgrade codes, no changes (%s)', have_scan_key) return '' # we have scanned this before and no new changes. # Go into each squid upgrade code and find all the related product codes. log.debug('Scan for upgrade codes (%s) for product codes', have_scan_key) for upgrade_code_squid in squid_upgrade_code_all: upgrade_code_guid = self.__squid_to_guid(upgrade_code_squid) pc_handle = win32api.RegOpenKeyEx(uc_handle, # pylint: disable=no-member upgrade_code_squid, 0, win32con.KEY_READ | self.__reg_32bit_access) _, pc_val_count, _ = win32api.RegQueryInfoKey(pc_handle) # pylint: disable=no-member for item_index in range(pc_val_count): product_code_guid = \ self.__squid_to_guid(win32api.RegEnumValue(pc_handle, item_index)[0]) # pylint: disable=no-member if product_code_guid: self.__upgrade_codes[product_code_guid] = upgrade_code_guid win32api.RegCloseKey(pc_handle) # pylint: disable=no-member win32api.RegCloseKey(uc_handle) # pylint: disable=no-member self.__upgrade_code_have_scan[have_scan_key] = (squid_upgrade_code_all, suc_pytime) return self.__upgrade_codes.get(self.__reg_key_guid, '')
[ "def", "upgrade_code", "(", "self", ")", ":", "if", "not", "self", ".", "__squid", ":", "# Must have a valid squid for an upgrade code to exist", "return", "''", "# GUID/SQUID are unique, so it does not matter if they are 32bit or", "# 64bit or user install so all items are cached in...
For installers which follow the Microsoft Installer standard, returns the ``Upgrade code``. Returns: value (str): ``Upgrade code`` GUID for installed software.
[ "For", "installers", "which", "follow", "the", "Microsoft", "Installer", "standard", "returns", "the", "Upgrade", "code", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L423-L484
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.list_patches
def list_patches(self): ''' For installers which follow the Microsoft Installer standard, returns a list of patches applied. Returns: value (list): Long name of the patch. ''' if not self.__squid: # Must have a valid squid for an upgrade code to exist return [] if self.__patch_list is None: # Read in the upgrade codes in this section of the reg. try: pat_all_handle = win32api.RegOpenKeyEx(getattr(win32con, self.__reg_hive), # pylint: disable=no-member self.__reg_patches_path, 0, win32con.KEY_READ | self.__reg_32bit_access) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found log.warning( 'Not Found %s\\%s 32bit %s', self.__reg_hive, self.__reg_patches_path, self.__reg_32bit ) return [] raise pc_sub_key_cnt, _, _ = win32api.RegQueryInfoKey(pat_all_handle) # pylint: disable=no-member if not pc_sub_key_cnt: return [] squid_patch_all, _, _, _ = zip(*win32api.RegEnumKeyEx(pat_all_handle)) # pylint: disable=no-member ret = [] # Scan the patches for the DisplayName of active patches. for patch_squid in squid_patch_all: try: patch_squid_handle = win32api.RegOpenKeyEx( # pylint: disable=no-member pat_all_handle, patch_squid, 0, win32con.KEY_READ | self.__reg_32bit_access) patch_display_name, patch_display_name_type = \ self.__reg_query_value(patch_squid_handle, 'DisplayName') patch_state, patch_state_type = self.__reg_query_value(patch_squid_handle, 'State') if (patch_state_type != win32con.REG_DWORD or not isinstance(patch_state_type, six.integer_types) or patch_state != 1 or # 1 is Active, 2 is Superseded/Obsolute patch_display_name_type != win32con.REG_SZ): continue win32api.RegCloseKey(patch_squid_handle) # pylint: disable=no-member ret.append(patch_display_name) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: log.debug('skipped patch, not found %s', patch_squid) continue raise return ret
python
def list_patches(self): ''' For installers which follow the Microsoft Installer standard, returns a list of patches applied. Returns: value (list): Long name of the patch. ''' if not self.__squid: # Must have a valid squid for an upgrade code to exist return [] if self.__patch_list is None: # Read in the upgrade codes in this section of the reg. try: pat_all_handle = win32api.RegOpenKeyEx(getattr(win32con, self.__reg_hive), # pylint: disable=no-member self.__reg_patches_path, 0, win32con.KEY_READ | self.__reg_32bit_access) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found log.warning( 'Not Found %s\\%s 32bit %s', self.__reg_hive, self.__reg_patches_path, self.__reg_32bit ) return [] raise pc_sub_key_cnt, _, _ = win32api.RegQueryInfoKey(pat_all_handle) # pylint: disable=no-member if not pc_sub_key_cnt: return [] squid_patch_all, _, _, _ = zip(*win32api.RegEnumKeyEx(pat_all_handle)) # pylint: disable=no-member ret = [] # Scan the patches for the DisplayName of active patches. for patch_squid in squid_patch_all: try: patch_squid_handle = win32api.RegOpenKeyEx( # pylint: disable=no-member pat_all_handle, patch_squid, 0, win32con.KEY_READ | self.__reg_32bit_access) patch_display_name, patch_display_name_type = \ self.__reg_query_value(patch_squid_handle, 'DisplayName') patch_state, patch_state_type = self.__reg_query_value(patch_squid_handle, 'State') if (patch_state_type != win32con.REG_DWORD or not isinstance(patch_state_type, six.integer_types) or patch_state != 1 or # 1 is Active, 2 is Superseded/Obsolute patch_display_name_type != win32con.REG_SZ): continue win32api.RegCloseKey(patch_squid_handle) # pylint: disable=no-member ret.append(patch_display_name) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: log.debug('skipped patch, not found %s', patch_squid) continue raise return ret
[ "def", "list_patches", "(", "self", ")", ":", "if", "not", "self", ".", "__squid", ":", "# Must have a valid squid for an upgrade code to exist", "return", "[", "]", "if", "self", ".", "__patch_list", "is", "None", ":", "# Read in the upgrade codes in this section of th...
For installers which follow the Microsoft Installer standard, returns a list of patches applied. Returns: value (list): Long name of the patch.
[ "For", "installers", "which", "follow", "the", "Microsoft", "Installer", "standard", "returns", "a", "list", "of", "patches", "applied", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L487-L548
train
saltstack/salt
salt/utils/pkg/win.py
RegSoftwareInfo.version_binary
def version_binary(self): ''' Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found ''' # Under MSI 'Version' is a 'REG_DWORD' which then sets other registry # values like DisplayVersion to x.x.x to the same value. # However not everyone plays by the rules, so we need to check first. # version_binary_data will be None if the reg value does not exist. # Some installs set 'Version' to REG_SZ (string) which is not # the MSI standard try: item_value, item_type = self.__reg_query_value(self.__reg_uninstall_handle, 'version') except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found return '', '' version_binary_text = '' version_src = '' if item_value: if item_type == win32con.REG_DWORD: if isinstance(item_value, six.integer_types): version_binary_raw = item_value if version_binary_raw: # Major.Minor.Build version_binary_text = '{0}.{1}.{2}'.format( version_binary_raw >> 24 & 0xff, version_binary_raw >> 16 & 0xff, version_binary_raw & 0xffff) version_src = 'binary-version' elif (item_type == win32con.REG_SZ and isinstance(item_value, six.string_types) and self.__version_pattern.match(item_value) is not None): # Hey, version should be a int/REG_DWORD, an installer has set # it to a string version_binary_text = item_value.strip(' ') version_src = 'binary-version (string)' return (version_binary_text, version_src)
python
def version_binary(self): ''' Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found ''' # Under MSI 'Version' is a 'REG_DWORD' which then sets other registry # values like DisplayVersion to x.x.x to the same value. # However not everyone plays by the rules, so we need to check first. # version_binary_data will be None if the reg value does not exist. # Some installs set 'Version' to REG_SZ (string) which is not # the MSI standard try: item_value, item_type = self.__reg_query_value(self.__reg_uninstall_handle, 'version') except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found return '', '' version_binary_text = '' version_src = '' if item_value: if item_type == win32con.REG_DWORD: if isinstance(item_value, six.integer_types): version_binary_raw = item_value if version_binary_raw: # Major.Minor.Build version_binary_text = '{0}.{1}.{2}'.format( version_binary_raw >> 24 & 0xff, version_binary_raw >> 16 & 0xff, version_binary_raw & 0xffff) version_src = 'binary-version' elif (item_type == win32con.REG_SZ and isinstance(item_value, six.string_types) and self.__version_pattern.match(item_value) is not None): # Hey, version should be a int/REG_DWORD, an installer has set # it to a string version_binary_text = item_value.strip(' ') version_src = 'binary-version (string)' return (version_binary_text, version_src)
[ "def", "version_binary", "(", "self", ")", ":", "# Under MSI 'Version' is a 'REG_DWORD' which then sets other registry", "# values like DisplayVersion to x.x.x to the same value.", "# However not everyone plays by the rules, so we need to check first.", "# version_binary_data will be None if the r...
Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found
[ "Return", "version", "number", "which", "is", "stored", "in", "binary", "format", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L601-L643
train
saltstack/salt
salt/utils/pkg/win.py
WinSoftware.pkg_version_list
def pkg_version_list(self, pkg_id): ''' Returns information on a package. Args: pkg_id (str): Package Id of the software/component. Returns: list: List of version numbers installed. ''' pkg_data = self.__reg_software.get(pkg_id, None) if not pkg_data: return [] if isinstance(pkg_data, list): # raw data is 'pkgid': [sorted version list] return pkg_data # already sorted oldest to newest # Must be a dict or OrderDict, and contain full details installed_versions = list(pkg_data.get('version').keys()) return sorted(installed_versions, key=cmp_to_key(self.__oldest_to_latest_version))
python
def pkg_version_list(self, pkg_id): ''' Returns information on a package. Args: pkg_id (str): Package Id of the software/component. Returns: list: List of version numbers installed. ''' pkg_data = self.__reg_software.get(pkg_id, None) if not pkg_data: return [] if isinstance(pkg_data, list): # raw data is 'pkgid': [sorted version list] return pkg_data # already sorted oldest to newest # Must be a dict or OrderDict, and contain full details installed_versions = list(pkg_data.get('version').keys()) return sorted(installed_versions, key=cmp_to_key(self.__oldest_to_latest_version))
[ "def", "pkg_version_list", "(", "self", ",", "pkg_id", ")", ":", "pkg_data", "=", "self", ".", "__reg_software", ".", "get", "(", "pkg_id", ",", "None", ")", "if", "not", "pkg_data", ":", "return", "[", "]", "if", "isinstance", "(", "pkg_data", ",", "l...
Returns information on a package. Args: pkg_id (str): Package Id of the software/component. Returns: list: List of version numbers installed.
[ "Returns", "information", "on", "a", "package", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L803-L823
train
saltstack/salt
salt/utils/pkg/win.py
WinSoftware.__sid_to_username
def __sid_to_username(sid): ''' Provided with a valid Windows Security Identifier (SID) and returns a Username Args: sid (str): Security Identifier (SID). Returns: str: Username in the format of username@realm or username@computer. ''' if sid is None or sid == '': return '' try: sid_bin = win32security.GetBinarySid(sid) # pylint: disable=no-member except pywintypes.error as exc: # pylint: disable=no-member raise ValueError( 'pkg: Software owned by {0} is not valid: [{1}] {2}'.format(sid, exc.winerror, exc.strerror) ) try: name, domain, _account_type = win32security.LookupAccountSid(None, sid_bin) # pylint: disable=no-member user_name = '{0}\\{1}'.format(domain, name) except pywintypes.error as exc: # pylint: disable=no-member # if user does not exist... # winerror.ERROR_NONE_MAPPED = No mapping between account names and # security IDs was carried out. if exc.winerror == winerror.ERROR_NONE_MAPPED: # 1332 # As the sid is from the registry it should be valid # even if it cannot be lookedup, so the sid is returned return sid else: raise ValueError( 'Failed looking up sid \'{0}\' username: [{1}] {2}'.format(sid, exc.winerror, exc.strerror) ) try: user_principal = win32security.TranslateName( # pylint: disable=no-member user_name, win32api.NameSamCompatible, # pylint: disable=no-member win32api.NameUserPrincipal) # pylint: disable=no-member except pywintypes.error as exc: # pylint: disable=no-member # winerror.ERROR_NO_SUCH_DOMAIN The specified domain either does not exist # or could not be contacted, computer may not be part of a domain also # winerror.ERROR_INVALID_DOMAINNAME The format of the specified domain name is # invalid. e.g. S-1-5-19 which is a local account # winerror.ERROR_NONE_MAPPED No mapping between account names and security IDs was done. if exc.winerror in (winerror.ERROR_NO_SUCH_DOMAIN, winerror.ERROR_INVALID_DOMAINNAME, winerror.ERROR_NONE_MAPPED): return '{0}@{1}'.format(name.lower(), domain.lower()) else: raise return user_principal
python
def __sid_to_username(sid): ''' Provided with a valid Windows Security Identifier (SID) and returns a Username Args: sid (str): Security Identifier (SID). Returns: str: Username in the format of username@realm or username@computer. ''' if sid is None or sid == '': return '' try: sid_bin = win32security.GetBinarySid(sid) # pylint: disable=no-member except pywintypes.error as exc: # pylint: disable=no-member raise ValueError( 'pkg: Software owned by {0} is not valid: [{1}] {2}'.format(sid, exc.winerror, exc.strerror) ) try: name, domain, _account_type = win32security.LookupAccountSid(None, sid_bin) # pylint: disable=no-member user_name = '{0}\\{1}'.format(domain, name) except pywintypes.error as exc: # pylint: disable=no-member # if user does not exist... # winerror.ERROR_NONE_MAPPED = No mapping between account names and # security IDs was carried out. if exc.winerror == winerror.ERROR_NONE_MAPPED: # 1332 # As the sid is from the registry it should be valid # even if it cannot be lookedup, so the sid is returned return sid else: raise ValueError( 'Failed looking up sid \'{0}\' username: [{1}] {2}'.format(sid, exc.winerror, exc.strerror) ) try: user_principal = win32security.TranslateName( # pylint: disable=no-member user_name, win32api.NameSamCompatible, # pylint: disable=no-member win32api.NameUserPrincipal) # pylint: disable=no-member except pywintypes.error as exc: # pylint: disable=no-member # winerror.ERROR_NO_SUCH_DOMAIN The specified domain either does not exist # or could not be contacted, computer may not be part of a domain also # winerror.ERROR_INVALID_DOMAINNAME The format of the specified domain name is # invalid. e.g. S-1-5-19 which is a local account # winerror.ERROR_NONE_MAPPED No mapping between account names and security IDs was done. if exc.winerror in (winerror.ERROR_NO_SUCH_DOMAIN, winerror.ERROR_INVALID_DOMAINNAME, winerror.ERROR_NONE_MAPPED): return '{0}@{1}'.format(name.lower(), domain.lower()) else: raise return user_principal
[ "def", "__sid_to_username", "(", "sid", ")", ":", "if", "sid", "is", "None", "or", "sid", "==", "''", ":", "return", "''", "try", ":", "sid_bin", "=", "win32security", ".", "GetBinarySid", "(", "sid", ")", "# pylint: disable=no-member", "except", "pywintypes...
Provided with a valid Windows Security Identifier (SID) and returns a Username Args: sid (str): Security Identifier (SID). Returns: str: Username in the format of username@realm or username@computer.
[ "Provided", "with", "a", "valid", "Windows", "Security", "Identifier", "(", "SID", ")", "and", "returns", "a", "Username" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L852-L902
train
saltstack/salt
salt/utils/pkg/win.py
WinSoftware.__software_to_pkg_id
def __software_to_pkg_id(self, publisher, name, is_component, is_32bit): ''' Determine the Package ID of a software/component using the software/component ``publisher``, ``name``, whether its a software or a component, and if its 32bit or 64bit archiecture. Args: publisher (str): Publisher of the software/component. name (str): Name of the software. is_component (bool): True if package is a component. is_32bit (bool): True if the software/component is 32bit architecture. Returns: str: Package Id ''' if publisher: # remove , and lowercase as , are used as list separators pub_lc = publisher.replace(',', '').lower() else: # remove , and lowercase pub_lc = 'NoValue' # Capitals/Special Value if name: name_lc = name.replace(',', '').lower() # remove , OR we do the URL Encode on chars we do not want e.g. \\ and , else: name_lc = 'NoValue' # Capitals/Special Value if is_component: soft_type = 'comp' else: soft_type = 'soft' if is_32bit: soft_type += '32' # Tag only the 32bit only default_pkg_id = pub_lc+'\\\\'+name_lc+'\\\\'+soft_type # Check to see if class was initialise with pkg_obj with a method called # to_pkg_id, and if so use it for the naming standard instead of the default if self.__pkg_obj and hasattr(self.__pkg_obj, 'to_pkg_id'): pkg_id = self.__pkg_obj.to_pkg_id(publisher, name, is_component, is_32bit) if pkg_id: return pkg_id return default_pkg_id
python
def __software_to_pkg_id(self, publisher, name, is_component, is_32bit): ''' Determine the Package ID of a software/component using the software/component ``publisher``, ``name``, whether its a software or a component, and if its 32bit or 64bit archiecture. Args: publisher (str): Publisher of the software/component. name (str): Name of the software. is_component (bool): True if package is a component. is_32bit (bool): True if the software/component is 32bit architecture. Returns: str: Package Id ''' if publisher: # remove , and lowercase as , are used as list separators pub_lc = publisher.replace(',', '').lower() else: # remove , and lowercase pub_lc = 'NoValue' # Capitals/Special Value if name: name_lc = name.replace(',', '').lower() # remove , OR we do the URL Encode on chars we do not want e.g. \\ and , else: name_lc = 'NoValue' # Capitals/Special Value if is_component: soft_type = 'comp' else: soft_type = 'soft' if is_32bit: soft_type += '32' # Tag only the 32bit only default_pkg_id = pub_lc+'\\\\'+name_lc+'\\\\'+soft_type # Check to see if class was initialise with pkg_obj with a method called # to_pkg_id, and if so use it for the naming standard instead of the default if self.__pkg_obj and hasattr(self.__pkg_obj, 'to_pkg_id'): pkg_id = self.__pkg_obj.to_pkg_id(publisher, name, is_component, is_32bit) if pkg_id: return pkg_id return default_pkg_id
[ "def", "__software_to_pkg_id", "(", "self", ",", "publisher", ",", "name", ",", "is_component", ",", "is_32bit", ")", ":", "if", "publisher", ":", "# remove , and lowercase as , are used as list separators", "pub_lc", "=", "publisher", ".", "replace", "(", "','", ",...
Determine the Package ID of a software/component using the software/component ``publisher``, ``name``, whether its a software or a component, and if its 32bit or 64bit archiecture. Args: publisher (str): Publisher of the software/component. name (str): Name of the software. is_component (bool): True if package is a component. is_32bit (bool): True if the software/component is 32bit architecture. Returns: str: Package Id
[ "Determine", "the", "Package", "ID", "of", "a", "software", "/", "component", "using", "the", "software", "/", "component", "publisher", "name", "whether", "its", "a", "software", "or", "a", "component", "and", "if", "its", "32bit", "or", "64bit", "archiectu...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L904-L950
train
saltstack/salt
salt/utils/pkg/win.py
WinSoftware.__version_capture_slp
def __version_capture_slp(self, pkg_id, version_binary, version_display, display_name): ''' This returns the version and where the version string came from, based on instructions under ``version_capture``, if ``version_capture`` is missing, it defaults to value of display-version. Args: pkg_id (str): Publisher of the software/component. version_binary (str): Name of the software. version_display (str): True if package is a component. display_name (str): True if the software/component is 32bit architecture. Returns: str: Package Id ''' if self.__pkg_obj and hasattr(self.__pkg_obj, 'version_capture'): version_str, src, version_user_str = \ self.__pkg_obj.version_capture(pkg_id, version_binary, version_display, display_name) if src != 'use-default' and version_str and src: return version_str, src, version_user_str elif src != 'use-default': raise ValueError( 'version capture within object \'{0}\' failed ' 'for pkg id: \'{1}\' it returned \'{2}\' \'{3}\' ' '\'{4}\''.format(six.text_type(self.__pkg_obj), pkg_id, version_str, src, version_user_str) ) # If self.__pkg_obj.version_capture() not defined defaults to using # version_display and if not valid then use version_binary, and as a last # result provide the version 0.0.0.0.0 to indicate version string was not determined. if version_display and re.match(r'\d+', version_display, flags=re.IGNORECASE + re.UNICODE) is not None: version_str = version_display src = 'display-version' elif version_binary and re.match(r'\d+', version_binary, flags=re.IGNORECASE + re.UNICODE) is not None: version_str = version_binary src = 'version-binary' else: src = 'none' version_str = '0.0.0.0.0' # return version str, src of the version, "user" interpretation of the version # which by default is version_str return version_str, src, version_str
python
def __version_capture_slp(self, pkg_id, version_binary, version_display, display_name): ''' This returns the version and where the version string came from, based on instructions under ``version_capture``, if ``version_capture`` is missing, it defaults to value of display-version. Args: pkg_id (str): Publisher of the software/component. version_binary (str): Name of the software. version_display (str): True if package is a component. display_name (str): True if the software/component is 32bit architecture. Returns: str: Package Id ''' if self.__pkg_obj and hasattr(self.__pkg_obj, 'version_capture'): version_str, src, version_user_str = \ self.__pkg_obj.version_capture(pkg_id, version_binary, version_display, display_name) if src != 'use-default' and version_str and src: return version_str, src, version_user_str elif src != 'use-default': raise ValueError( 'version capture within object \'{0}\' failed ' 'for pkg id: \'{1}\' it returned \'{2}\' \'{3}\' ' '\'{4}\''.format(six.text_type(self.__pkg_obj), pkg_id, version_str, src, version_user_str) ) # If self.__pkg_obj.version_capture() not defined defaults to using # version_display and if not valid then use version_binary, and as a last # result provide the version 0.0.0.0.0 to indicate version string was not determined. if version_display and re.match(r'\d+', version_display, flags=re.IGNORECASE + re.UNICODE) is not None: version_str = version_display src = 'display-version' elif version_binary and re.match(r'\d+', version_binary, flags=re.IGNORECASE + re.UNICODE) is not None: version_str = version_binary src = 'version-binary' else: src = 'none' version_str = '0.0.0.0.0' # return version str, src of the version, "user" interpretation of the version # which by default is version_str return version_str, src, version_str
[ "def", "__version_capture_slp", "(", "self", ",", "pkg_id", ",", "version_binary", ",", "version_display", ",", "display_name", ")", ":", "if", "self", ".", "__pkg_obj", "and", "hasattr", "(", "self", ".", "__pkg_obj", ",", "'version_capture'", ")", ":", "vers...
This returns the version and where the version string came from, based on instructions under ``version_capture``, if ``version_capture`` is missing, it defaults to value of display-version. Args: pkg_id (str): Publisher of the software/component. version_binary (str): Name of the software. version_display (str): True if package is a component. display_name (str): True if the software/component is 32bit architecture. Returns: str: Package Id
[ "This", "returns", "the", "version", "and", "where", "the", "version", "string", "came", "from", "based", "on", "instructions", "under", "version_capture", "if", "version_capture", "is", "missing", "it", "defaults", "to", "value", "of", "display", "-", "version"...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L952-L993
train
saltstack/salt
salt/utils/pkg/win.py
WinSoftware.__collect_software_info
def __collect_software_info(self, sid, key_software, use_32bit): ''' Update data with the next software found ''' reg_soft_info = RegSoftwareInfo(key_software, sid, use_32bit) # Check if the registry entry is a valid. # a) Cannot manage software without at least a display name display_name = reg_soft_info.get_install_value('DisplayName', wanted_type='str') if display_name is None or self.__whitespace_pattern.match(display_name): return # b) make sure its not an 'Hotfix', 'Update Rollup', 'Security Update', 'ServicePack' # General this is software which pre dates Windows 10 default_value = reg_soft_info.get_install_value('', wanted_type='str') release_type = reg_soft_info.get_install_value('ReleaseType', wanted_type='str') if (re.match(r'^{.*\}\.KB\d{6,}$', key_software, flags=re.IGNORECASE + re.UNICODE) is not None or (default_value and default_value.startswith(('KB', 'kb', 'Kb'))) or (release_type and release_type in ('Hotfix', 'Update Rollup', 'Security Update', 'ServicePack'))): log.debug('skipping hotfix/update/service pack %s', key_software) return # if NoRemove exists we would expect their to be no UninstallString uninstall_no_remove = reg_soft_info.is_install_true('NoRemove') uninstall_string = reg_soft_info.get_install_value('UninstallString') uninstall_quiet_string = reg_soft_info.get_install_value('QuietUninstallString') uninstall_modify_path = reg_soft_info.get_install_value('ModifyPath') windows_installer = reg_soft_info.is_install_true('WindowsInstaller') system_component = reg_soft_info.is_install_true('SystemComponent') publisher = reg_soft_info.get_install_value('Publisher', wanted_type='str') # UninstallString is optional if the installer is "windows installer"/MSI # However for it to appear in Control-Panel -> Program and Features -> Uninstall or change a program # the UninstallString needs to be set or ModifyPath set if (uninstall_string is None and uninstall_quiet_string is None and uninstall_modify_path is None and (not windows_installer)): return # Question: If uninstall string is not set and windows_installer should we set it # Question: if uninstall_quiet is not set ....... if sid: username = self.__sid_to_username(sid) else: username = None # We now have a valid software install or a system component pkg_id = self.__software_to_pkg_id(publisher, display_name, system_component, use_32bit) version_binary, version_src = reg_soft_info.version_binary version_display = reg_soft_info.get_install_value('DisplayVersion', wanted_type='str') # version_capture is what the slp defines, the result overrides. Question: maybe it should error if it fails? (version_text, version_src, user_version) = \ self.__version_capture_slp(pkg_id, version_binary, version_display, display_name) if not user_version: user_version = version_text # log.trace('%s\\%s ver:%s src:%s', username or 'SYSTEM', pkg_id, version_text, version_src) if username: dict_key = '{};{}'.format(username, pkg_id) # Use ; as its not a valid hostnmae char else: dict_key = pkg_id # Guessing the architecture http://helpnet.flexerasoftware.com/isxhelp21/helplibrary/IHelp64BitSupport.htm # A 32 bit installed.exe can install a 64 bit app, but for it to write to 64bit reg it will # need to use WOW. So the following is a bit of a guess if self.__version_only: # package name and package version list, are the only info being return if dict_key in self.__reg_software: if version_text not in self.__reg_software[dict_key]: # Not expecting the list to be big, simple search and insert insert_point = 0 for ver_item in self.__reg_software[dict_key]: if LooseVersion(version_text) <= LooseVersion(ver_item): break insert_point += 1 self.__reg_software[dict_key].insert(insert_point, version_text) else: # This code is here as it can happen, especially if the # package id provided by pkg_obj is simple. log.debug( 'Found extra entries for \'%s\' with same version ' '\'%s\', skipping entry \'%s\'', dict_key, version_text, key_software ) else: self.__reg_software[dict_key] = [version_text] return if dict_key in self.__reg_software: data = self.__reg_software[dict_key] else: data = self.__reg_software[dict_key] = OrderedDict() if sid: # HKEY_USERS has no 32bit and 64bit view like HKEY_LOCAL_MACHINE data.update({'arch': 'unknown'}) else: arch_str = 'x86' if use_32bit else 'x64' if 'arch' in data: if data['arch'] != arch_str: data['arch'] = 'many' else: data.update({'arch': arch_str}) if publisher: if 'vendor' in data: if data['vendor'].lower() != publisher.lower(): data['vendor'] = 'many' else: data['vendor'] = publisher if 'win_system_component' in data: if data['win_system_component'] != system_component: data['win_system_component'] = None else: data['win_system_component'] = system_component data.update({'win_version_src': version_src}) data.setdefault('version', {}) if version_text in data['version']: if 'win_install_count' in data['version'][version_text]: data['version'][version_text]['win_install_count'] += 1 else: # This is only defined when we have the same item already data['version'][version_text]['win_install_count'] = 2 else: data['version'][version_text] = OrderedDict() version_data = data['version'][version_text] version_data.update({'win_display_name': display_name}) if uninstall_string: version_data.update({'win_uninstall_cmd': uninstall_string}) if uninstall_quiet_string: version_data.update({'win_uninstall_quiet_cmd': uninstall_quiet_string}) if uninstall_no_remove: version_data.update({'win_uninstall_no_remove': uninstall_no_remove}) version_data.update({'win_product_code': key_software}) if version_display: version_data.update({'win_version_display': version_display}) if version_binary: version_data.update({'win_version_binary': version_binary}) if user_version: version_data.update({'win_version_user': user_version}) # Determine Installer Product # 'NSIS:Language' # 'Inno Setup: Setup Version' if (windows_installer or (uninstall_string and re.search(r'MsiExec.exe\s|MsiExec\s', uninstall_string, flags=re.IGNORECASE + re.UNICODE))): version_data.update({'win_installer_type': 'winmsi'}) elif (re.match(r'InstallShield_', key_software, re.IGNORECASE) is not None or (uninstall_string and ( re.search(r'InstallShield', uninstall_string, flags=re.IGNORECASE + re.UNICODE) is not None or re.search(r'isuninst\.exe.*\.isu', uninstall_string, flags=re.IGNORECASE + re.UNICODE) is not None) ) ): version_data.update({'win_installer_type': 'installshield'}) elif (key_software.endswith('_is1') and reg_soft_info.get_install_value('Inno Setup: Setup Version', wanted_type='str')): version_data.update({'win_installer_type': 'inno'}) elif (uninstall_string and re.search(r'.*\\uninstall.exe|.*\\uninst.exe', uninstall_string, flags=re.IGNORECASE + re.UNICODE)): version_data.update({'win_installer_type': 'nsis'}) else: version_data.update({'win_installer_type': 'unknown'}) # Update dict with information retrieved so far for detail results to be return # Do not add fields which are blank. language_number = reg_soft_info.get_install_value('Language') if isinstance(language_number, six.integer_types) and language_number in locale.windows_locale: version_data.update({'win_language': locale.windows_locale[language_number]}) package_code = reg_soft_info.package_code if package_code: version_data.update({'win_package_code': package_code}) upgrade_code = reg_soft_info.upgrade_code if upgrade_code: version_data.update({'win_upgrade_code': upgrade_code}) is_minor_upgrade = reg_soft_info.is_install_true('IsMinorUpgrade') if is_minor_upgrade: version_data.update({'win_is_minor_upgrade': is_minor_upgrade}) install_time = reg_soft_info.install_time if install_time: version_data.update({'install_date': datetime.datetime.fromtimestamp(install_time).isoformat()}) version_data.update({'install_date_time_t': int(install_time)}) for infokey, infotype, regfield_list in self.__uninstall_search_list: for regfield in regfield_list: strvalue = reg_soft_info.get_install_value(regfield, wanted_type=infotype) if strvalue: version_data.update({infokey: strvalue}) break for infokey, infotype, regfield_list in self.__products_search_list: for regfield in regfield_list: data = reg_soft_info.get_product_value(regfield, wanted_type=infotype) if data is not None: version_data.update({infokey: data}) break patch_list = reg_soft_info.list_patches if patch_list: version_data.update({'win_patches': patch_list})
python
def __collect_software_info(self, sid, key_software, use_32bit): ''' Update data with the next software found ''' reg_soft_info = RegSoftwareInfo(key_software, sid, use_32bit) # Check if the registry entry is a valid. # a) Cannot manage software without at least a display name display_name = reg_soft_info.get_install_value('DisplayName', wanted_type='str') if display_name is None or self.__whitespace_pattern.match(display_name): return # b) make sure its not an 'Hotfix', 'Update Rollup', 'Security Update', 'ServicePack' # General this is software which pre dates Windows 10 default_value = reg_soft_info.get_install_value('', wanted_type='str') release_type = reg_soft_info.get_install_value('ReleaseType', wanted_type='str') if (re.match(r'^{.*\}\.KB\d{6,}$', key_software, flags=re.IGNORECASE + re.UNICODE) is not None or (default_value and default_value.startswith(('KB', 'kb', 'Kb'))) or (release_type and release_type in ('Hotfix', 'Update Rollup', 'Security Update', 'ServicePack'))): log.debug('skipping hotfix/update/service pack %s', key_software) return # if NoRemove exists we would expect their to be no UninstallString uninstall_no_remove = reg_soft_info.is_install_true('NoRemove') uninstall_string = reg_soft_info.get_install_value('UninstallString') uninstall_quiet_string = reg_soft_info.get_install_value('QuietUninstallString') uninstall_modify_path = reg_soft_info.get_install_value('ModifyPath') windows_installer = reg_soft_info.is_install_true('WindowsInstaller') system_component = reg_soft_info.is_install_true('SystemComponent') publisher = reg_soft_info.get_install_value('Publisher', wanted_type='str') # UninstallString is optional if the installer is "windows installer"/MSI # However for it to appear in Control-Panel -> Program and Features -> Uninstall or change a program # the UninstallString needs to be set or ModifyPath set if (uninstall_string is None and uninstall_quiet_string is None and uninstall_modify_path is None and (not windows_installer)): return # Question: If uninstall string is not set and windows_installer should we set it # Question: if uninstall_quiet is not set ....... if sid: username = self.__sid_to_username(sid) else: username = None # We now have a valid software install or a system component pkg_id = self.__software_to_pkg_id(publisher, display_name, system_component, use_32bit) version_binary, version_src = reg_soft_info.version_binary version_display = reg_soft_info.get_install_value('DisplayVersion', wanted_type='str') # version_capture is what the slp defines, the result overrides. Question: maybe it should error if it fails? (version_text, version_src, user_version) = \ self.__version_capture_slp(pkg_id, version_binary, version_display, display_name) if not user_version: user_version = version_text # log.trace('%s\\%s ver:%s src:%s', username or 'SYSTEM', pkg_id, version_text, version_src) if username: dict_key = '{};{}'.format(username, pkg_id) # Use ; as its not a valid hostnmae char else: dict_key = pkg_id # Guessing the architecture http://helpnet.flexerasoftware.com/isxhelp21/helplibrary/IHelp64BitSupport.htm # A 32 bit installed.exe can install a 64 bit app, but for it to write to 64bit reg it will # need to use WOW. So the following is a bit of a guess if self.__version_only: # package name and package version list, are the only info being return if dict_key in self.__reg_software: if version_text not in self.__reg_software[dict_key]: # Not expecting the list to be big, simple search and insert insert_point = 0 for ver_item in self.__reg_software[dict_key]: if LooseVersion(version_text) <= LooseVersion(ver_item): break insert_point += 1 self.__reg_software[dict_key].insert(insert_point, version_text) else: # This code is here as it can happen, especially if the # package id provided by pkg_obj is simple. log.debug( 'Found extra entries for \'%s\' with same version ' '\'%s\', skipping entry \'%s\'', dict_key, version_text, key_software ) else: self.__reg_software[dict_key] = [version_text] return if dict_key in self.__reg_software: data = self.__reg_software[dict_key] else: data = self.__reg_software[dict_key] = OrderedDict() if sid: # HKEY_USERS has no 32bit and 64bit view like HKEY_LOCAL_MACHINE data.update({'arch': 'unknown'}) else: arch_str = 'x86' if use_32bit else 'x64' if 'arch' in data: if data['arch'] != arch_str: data['arch'] = 'many' else: data.update({'arch': arch_str}) if publisher: if 'vendor' in data: if data['vendor'].lower() != publisher.lower(): data['vendor'] = 'many' else: data['vendor'] = publisher if 'win_system_component' in data: if data['win_system_component'] != system_component: data['win_system_component'] = None else: data['win_system_component'] = system_component data.update({'win_version_src': version_src}) data.setdefault('version', {}) if version_text in data['version']: if 'win_install_count' in data['version'][version_text]: data['version'][version_text]['win_install_count'] += 1 else: # This is only defined when we have the same item already data['version'][version_text]['win_install_count'] = 2 else: data['version'][version_text] = OrderedDict() version_data = data['version'][version_text] version_data.update({'win_display_name': display_name}) if uninstall_string: version_data.update({'win_uninstall_cmd': uninstall_string}) if uninstall_quiet_string: version_data.update({'win_uninstall_quiet_cmd': uninstall_quiet_string}) if uninstall_no_remove: version_data.update({'win_uninstall_no_remove': uninstall_no_remove}) version_data.update({'win_product_code': key_software}) if version_display: version_data.update({'win_version_display': version_display}) if version_binary: version_data.update({'win_version_binary': version_binary}) if user_version: version_data.update({'win_version_user': user_version}) # Determine Installer Product # 'NSIS:Language' # 'Inno Setup: Setup Version' if (windows_installer or (uninstall_string and re.search(r'MsiExec.exe\s|MsiExec\s', uninstall_string, flags=re.IGNORECASE + re.UNICODE))): version_data.update({'win_installer_type': 'winmsi'}) elif (re.match(r'InstallShield_', key_software, re.IGNORECASE) is not None or (uninstall_string and ( re.search(r'InstallShield', uninstall_string, flags=re.IGNORECASE + re.UNICODE) is not None or re.search(r'isuninst\.exe.*\.isu', uninstall_string, flags=re.IGNORECASE + re.UNICODE) is not None) ) ): version_data.update({'win_installer_type': 'installshield'}) elif (key_software.endswith('_is1') and reg_soft_info.get_install_value('Inno Setup: Setup Version', wanted_type='str')): version_data.update({'win_installer_type': 'inno'}) elif (uninstall_string and re.search(r'.*\\uninstall.exe|.*\\uninst.exe', uninstall_string, flags=re.IGNORECASE + re.UNICODE)): version_data.update({'win_installer_type': 'nsis'}) else: version_data.update({'win_installer_type': 'unknown'}) # Update dict with information retrieved so far for detail results to be return # Do not add fields which are blank. language_number = reg_soft_info.get_install_value('Language') if isinstance(language_number, six.integer_types) and language_number in locale.windows_locale: version_data.update({'win_language': locale.windows_locale[language_number]}) package_code = reg_soft_info.package_code if package_code: version_data.update({'win_package_code': package_code}) upgrade_code = reg_soft_info.upgrade_code if upgrade_code: version_data.update({'win_upgrade_code': upgrade_code}) is_minor_upgrade = reg_soft_info.is_install_true('IsMinorUpgrade') if is_minor_upgrade: version_data.update({'win_is_minor_upgrade': is_minor_upgrade}) install_time = reg_soft_info.install_time if install_time: version_data.update({'install_date': datetime.datetime.fromtimestamp(install_time).isoformat()}) version_data.update({'install_date_time_t': int(install_time)}) for infokey, infotype, regfield_list in self.__uninstall_search_list: for regfield in regfield_list: strvalue = reg_soft_info.get_install_value(regfield, wanted_type=infotype) if strvalue: version_data.update({infokey: strvalue}) break for infokey, infotype, regfield_list in self.__products_search_list: for regfield in regfield_list: data = reg_soft_info.get_product_value(regfield, wanted_type=infotype) if data is not None: version_data.update({infokey: data}) break patch_list = reg_soft_info.list_patches if patch_list: version_data.update({'win_patches': patch_list})
[ "def", "__collect_software_info", "(", "self", ",", "sid", ",", "key_software", ",", "use_32bit", ")", ":", "reg_soft_info", "=", "RegSoftwareInfo", "(", "key_software", ",", "sid", ",", "use_32bit", ")", "# Check if the registry entry is a valid.", "# a) Cannot manage ...
Update data with the next software found
[ "Update", "data", "with", "the", "next", "software", "found" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L995-L1209
train
saltstack/salt
salt/utils/pkg/win.py
WinSoftware.__get_software_details
def __get_software_details(self, user_pkgs): ''' This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value .. sectionauthor:: Damon Atkins <https://github.com/damon-atkins> .. versionadded:: Carbon ''' # FUNCTION MAIN CODE # # Search 64bit, on 64bit platform, on 32bit its ignored. if platform.architecture()[0] == '32bit': # Handle Python 32bit on 64&32 bit platform and Python 64bit if win32process.IsWow64Process(): # pylint: disable=no-member # 32bit python on a 64bit platform use_32bit_lookup = {True: 0, False: win32con.KEY_WOW64_64KEY} arch_list = [True, False] else: # 32bit python on a 32bit platform use_32bit_lookup = {True: 0, False: None} arch_list = [True] else: # Python is 64bit therefore most be on 64bit System. use_32bit_lookup = {True: win32con.KEY_WOW64_32KEY, False: 0} arch_list = [True, False] # Process software installed for the machine i.e. all users. for arch_flag in arch_list: key_search = 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall' log.debug('SYSTEM processing 32bit:%s', arch_flag) handle = win32api.RegOpenKeyEx( # pylint: disable=no-member win32con.HKEY_LOCAL_MACHINE, key_search, 0, win32con.KEY_READ | use_32bit_lookup[arch_flag]) reg_key_all, _, _, _ = zip(*win32api.RegEnumKeyEx(handle)) # pylint: disable=no-member win32api.RegCloseKey(handle) # pylint: disable=no-member for reg_key in reg_key_all: self.__collect_software_info(None, reg_key, arch_flag) if not user_pkgs: return # Process software installed under all USERs, this adds significate processing time. # There is not 32/64 bit registry redirection under user tree. log.debug('Processing user software... please wait') handle_sid = win32api.RegOpenKeyEx( # pylint: disable=no-member win32con.HKEY_USERS, '', 0, win32con.KEY_READ) sid_all = [] for index in range(win32api.RegQueryInfoKey(handle_sid)[0]): # pylint: disable=no-member sid_all.append(win32api.RegEnumKey(handle_sid, index)) # pylint: disable=no-member for sid in sid_all: if self.__sid_pattern.match(sid) is not None: # S-1-5-18 needs to be ignored? user_uninstall_path = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'.format(sid) try: handle = win32api.RegOpenKeyEx( # pylint: disable=no-member handle_sid, user_uninstall_path, 0, win32con.KEY_READ) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found Uninstall under SID log.debug('Not Found %s', user_uninstall_path) continue else: raise try: reg_key_all, _, _, _ = zip(*win32api.RegEnumKeyEx(handle)) # pylint: disable=no-member except ValueError: log.debug('No Entries Found %s', user_uninstall_path) reg_key_all = [] win32api.RegCloseKey(handle) # pylint: disable=no-member for reg_key in reg_key_all: self.__collect_software_info(sid, reg_key, False) win32api.RegCloseKey(handle_sid) # pylint: disable=no-member return
python
def __get_software_details(self, user_pkgs): ''' This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value .. sectionauthor:: Damon Atkins <https://github.com/damon-atkins> .. versionadded:: Carbon ''' # FUNCTION MAIN CODE # # Search 64bit, on 64bit platform, on 32bit its ignored. if platform.architecture()[0] == '32bit': # Handle Python 32bit on 64&32 bit platform and Python 64bit if win32process.IsWow64Process(): # pylint: disable=no-member # 32bit python on a 64bit platform use_32bit_lookup = {True: 0, False: win32con.KEY_WOW64_64KEY} arch_list = [True, False] else: # 32bit python on a 32bit platform use_32bit_lookup = {True: 0, False: None} arch_list = [True] else: # Python is 64bit therefore most be on 64bit System. use_32bit_lookup = {True: win32con.KEY_WOW64_32KEY, False: 0} arch_list = [True, False] # Process software installed for the machine i.e. all users. for arch_flag in arch_list: key_search = 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall' log.debug('SYSTEM processing 32bit:%s', arch_flag) handle = win32api.RegOpenKeyEx( # pylint: disable=no-member win32con.HKEY_LOCAL_MACHINE, key_search, 0, win32con.KEY_READ | use_32bit_lookup[arch_flag]) reg_key_all, _, _, _ = zip(*win32api.RegEnumKeyEx(handle)) # pylint: disable=no-member win32api.RegCloseKey(handle) # pylint: disable=no-member for reg_key in reg_key_all: self.__collect_software_info(None, reg_key, arch_flag) if not user_pkgs: return # Process software installed under all USERs, this adds significate processing time. # There is not 32/64 bit registry redirection under user tree. log.debug('Processing user software... please wait') handle_sid = win32api.RegOpenKeyEx( # pylint: disable=no-member win32con.HKEY_USERS, '', 0, win32con.KEY_READ) sid_all = [] for index in range(win32api.RegQueryInfoKey(handle_sid)[0]): # pylint: disable=no-member sid_all.append(win32api.RegEnumKey(handle_sid, index)) # pylint: disable=no-member for sid in sid_all: if self.__sid_pattern.match(sid) is not None: # S-1-5-18 needs to be ignored? user_uninstall_path = '{0}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'.format(sid) try: handle = win32api.RegOpenKeyEx( # pylint: disable=no-member handle_sid, user_uninstall_path, 0, win32con.KEY_READ) except pywintypes.error as exc: # pylint: disable=no-member if exc.winerror == winerror.ERROR_FILE_NOT_FOUND: # Not Found Uninstall under SID log.debug('Not Found %s', user_uninstall_path) continue else: raise try: reg_key_all, _, _, _ = zip(*win32api.RegEnumKeyEx(handle)) # pylint: disable=no-member except ValueError: log.debug('No Entries Found %s', user_uninstall_path) reg_key_all = [] win32api.RegCloseKey(handle) # pylint: disable=no-member for reg_key in reg_key_all: self.__collect_software_info(sid, reg_key, False) win32api.RegCloseKey(handle_sid) # pylint: disable=no-member return
[ "def", "__get_software_details", "(", "self", ",", "user_pkgs", ")", ":", "# FUNCTION MAIN CODE #", "# Search 64bit, on 64bit platform, on 32bit its ignored.", "if", "platform", ".", "architecture", "(", ")", "[", "0", "]", "==", "'32bit'", ":", "# Handle Python 32bit on ...
This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value .. sectionauthor:: Damon Atkins <https://github.com/damon-atkins> .. versionadded:: Carbon
[ "This", "searches", "the", "uninstall", "keys", "in", "the", "registry", "to", "find", "a", "match", "in", "the", "sub", "keys", "it", "will", "return", "a", "dict", "with", "the", "display", "name", "as", "the", "key", "and", "the", "version", "as", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/win.py#L1211-L1292
train
saltstack/salt
salt/utils/gitfs.py
enforce_types
def enforce_types(key, val): ''' Force params to be strings unless they should remain a different type ''' non_string_params = { 'ssl_verify': bool, 'insecure_auth': bool, 'disable_saltenv_mapping': bool, 'env_whitelist': 'stringlist', 'env_blacklist': 'stringlist', 'saltenv_whitelist': 'stringlist', 'saltenv_blacklist': 'stringlist', 'refspecs': 'stringlist', 'ref_types': 'stringlist', 'update_interval': int, } def _find_global(key): for item in non_string_params: try: if key.endswith('_' + item): ret = item break except TypeError: if key.endswith('_' + six.text_type(item)): ret = item break else: ret = None return ret if key not in non_string_params: key = _find_global(key) if key is None: return six.text_type(val) expected = non_string_params[key] if expected == 'stringlist': if not isinstance(val, (six.string_types, list)): val = six.text_type(val) if isinstance(val, six.string_types): return [x.strip() for x in val.split(',')] return [six.text_type(x) for x in val] else: try: return expected(val) except Exception as exc: log.error( 'Failed to enforce type for key=%s with val=%s, falling back ' 'to a string', key, val ) return six.text_type(val)
python
def enforce_types(key, val): ''' Force params to be strings unless they should remain a different type ''' non_string_params = { 'ssl_verify': bool, 'insecure_auth': bool, 'disable_saltenv_mapping': bool, 'env_whitelist': 'stringlist', 'env_blacklist': 'stringlist', 'saltenv_whitelist': 'stringlist', 'saltenv_blacklist': 'stringlist', 'refspecs': 'stringlist', 'ref_types': 'stringlist', 'update_interval': int, } def _find_global(key): for item in non_string_params: try: if key.endswith('_' + item): ret = item break except TypeError: if key.endswith('_' + six.text_type(item)): ret = item break else: ret = None return ret if key not in non_string_params: key = _find_global(key) if key is None: return six.text_type(val) expected = non_string_params[key] if expected == 'stringlist': if not isinstance(val, (six.string_types, list)): val = six.text_type(val) if isinstance(val, six.string_types): return [x.strip() for x in val.split(',')] return [six.text_type(x) for x in val] else: try: return expected(val) except Exception as exc: log.error( 'Failed to enforce type for key=%s with val=%s, falling back ' 'to a string', key, val ) return six.text_type(val)
[ "def", "enforce_types", "(", "key", ",", "val", ")", ":", "non_string_params", "=", "{", "'ssl_verify'", ":", "bool", ",", "'insecure_auth'", ":", "bool", ",", "'disable_saltenv_mapping'", ":", "bool", ",", "'env_whitelist'", ":", "'stringlist'", ",", "'env_blac...
Force params to be strings unless they should remain a different type
[ "Force", "params", "to", "be", "strings", "unless", "they", "should", "remain", "a", "different", "type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L153-L204
train
saltstack/salt
salt/utils/gitfs.py
GitProvider._get_envs_from_ref_paths
def _get_envs_from_ref_paths(self, refs): ''' Return the names of remote refs (stripped of the remote name) and tags which are map to the branches and tags. ''' def _check_ref(env_set, rname): ''' Add the appropriate saltenv(s) to the set ''' if rname in self.saltenv_revmap: env_set.update(self.saltenv_revmap[rname]) else: if rname == self.base: env_set.add('base') elif not self.disable_saltenv_mapping: env_set.add(rname) use_branches = 'branch' in self.ref_types use_tags = 'tag' in self.ref_types ret = set() if salt.utils.stringutils.is_hex(self.base): # gitfs_base or per-saltenv 'base' may point to a commit ID, which # would not show up in the refs. Make sure we include it. ret.add('base') for ref in salt.utils.data.decode(refs): if ref.startswith('refs/'): ref = ref[5:] rtype, rname = ref.split('/', 1) if rtype == 'remotes' and use_branches: parted = rname.partition('/') rname = parted[2] if parted[2] else parted[0] _check_ref(ret, rname) elif rtype == 'tags' and use_tags: _check_ref(ret, rname) return ret
python
def _get_envs_from_ref_paths(self, refs): ''' Return the names of remote refs (stripped of the remote name) and tags which are map to the branches and tags. ''' def _check_ref(env_set, rname): ''' Add the appropriate saltenv(s) to the set ''' if rname in self.saltenv_revmap: env_set.update(self.saltenv_revmap[rname]) else: if rname == self.base: env_set.add('base') elif not self.disable_saltenv_mapping: env_set.add(rname) use_branches = 'branch' in self.ref_types use_tags = 'tag' in self.ref_types ret = set() if salt.utils.stringutils.is_hex(self.base): # gitfs_base or per-saltenv 'base' may point to a commit ID, which # would not show up in the refs. Make sure we include it. ret.add('base') for ref in salt.utils.data.decode(refs): if ref.startswith('refs/'): ref = ref[5:] rtype, rname = ref.split('/', 1) if rtype == 'remotes' and use_branches: parted = rname.partition('/') rname = parted[2] if parted[2] else parted[0] _check_ref(ret, rname) elif rtype == 'tags' and use_tags: _check_ref(ret, rname) return ret
[ "def", "_get_envs_from_ref_paths", "(", "self", ",", "refs", ")", ":", "def", "_check_ref", "(", "env_set", ",", "rname", ")", ":", "'''\n Add the appropriate saltenv(s) to the set\n '''", "if", "rname", "in", "self", ".", "saltenv_revmap", ":", ...
Return the names of remote refs (stripped of the remote name) and tags which are map to the branches and tags.
[ "Return", "the", "names", "of", "remote", "refs", "(", "stripped", "of", "the", "remote", "name", ")", "and", "tags", "which", "are", "map", "to", "the", "branches", "and", "tags", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L467-L503
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.add_conf_overlay
def add_conf_overlay(cls, name): ''' Programmatically determine config value based on the desired saltenv ''' def _getconf(self, tgt_env='base'): strip_sep = lambda x: x.rstrip(os.sep) \ if name in ('root', 'mountpoint') \ else x if self.role != 'gitfs': return strip_sep(getattr(self, '_' + name)) # Get saltenv-specific configuration saltenv_conf = self.saltenv.get(tgt_env, {}) if name == 'ref': def _get_per_saltenv(tgt_env): if name in saltenv_conf: return saltenv_conf[name] elif tgt_env in self.global_saltenv \ and name in self.global_saltenv[tgt_env]: return self.global_saltenv[tgt_env][name] else: return None # Return the all_saltenvs branch/tag if it is configured per_saltenv_ref = _get_per_saltenv(tgt_env) try: all_saltenvs_ref = self.all_saltenvs if per_saltenv_ref and all_saltenvs_ref != per_saltenv_ref: log.debug( 'The per-saltenv configuration has mapped the ' '\'%s\' branch/tag to saltenv \'%s\' for %s ' 'remote \'%s\', but this remote has ' 'all_saltenvs set to \'%s\'. The per-saltenv ' 'mapping will be ignored in favor of \'%s\'.', per_saltenv_ref, tgt_env, self.role, self.id, all_saltenvs_ref, all_saltenvs_ref ) return all_saltenvs_ref except AttributeError: # all_saltenvs not configured for this remote pass if tgt_env == 'base': return self.base elif self.disable_saltenv_mapping: if per_saltenv_ref is None: log.debug( 'saltenv mapping is diabled for %s remote \'%s\' ' 'and saltenv \'%s\' is not explicitly mapped', self.role, self.id, tgt_env ) return per_saltenv_ref else: return per_saltenv_ref or tgt_env if name in saltenv_conf: return strip_sep(saltenv_conf[name]) elif tgt_env in self.global_saltenv \ and name in self.global_saltenv[tgt_env]: return strip_sep(self.global_saltenv[tgt_env][name]) else: return strip_sep(getattr(self, '_' + name)) setattr(cls, name, _getconf)
python
def add_conf_overlay(cls, name): ''' Programmatically determine config value based on the desired saltenv ''' def _getconf(self, tgt_env='base'): strip_sep = lambda x: x.rstrip(os.sep) \ if name in ('root', 'mountpoint') \ else x if self.role != 'gitfs': return strip_sep(getattr(self, '_' + name)) # Get saltenv-specific configuration saltenv_conf = self.saltenv.get(tgt_env, {}) if name == 'ref': def _get_per_saltenv(tgt_env): if name in saltenv_conf: return saltenv_conf[name] elif tgt_env in self.global_saltenv \ and name in self.global_saltenv[tgt_env]: return self.global_saltenv[tgt_env][name] else: return None # Return the all_saltenvs branch/tag if it is configured per_saltenv_ref = _get_per_saltenv(tgt_env) try: all_saltenvs_ref = self.all_saltenvs if per_saltenv_ref and all_saltenvs_ref != per_saltenv_ref: log.debug( 'The per-saltenv configuration has mapped the ' '\'%s\' branch/tag to saltenv \'%s\' for %s ' 'remote \'%s\', but this remote has ' 'all_saltenvs set to \'%s\'. The per-saltenv ' 'mapping will be ignored in favor of \'%s\'.', per_saltenv_ref, tgt_env, self.role, self.id, all_saltenvs_ref, all_saltenvs_ref ) return all_saltenvs_ref except AttributeError: # all_saltenvs not configured for this remote pass if tgt_env == 'base': return self.base elif self.disable_saltenv_mapping: if per_saltenv_ref is None: log.debug( 'saltenv mapping is diabled for %s remote \'%s\' ' 'and saltenv \'%s\' is not explicitly mapped', self.role, self.id, tgt_env ) return per_saltenv_ref else: return per_saltenv_ref or tgt_env if name in saltenv_conf: return strip_sep(saltenv_conf[name]) elif tgt_env in self.global_saltenv \ and name in self.global_saltenv[tgt_env]: return strip_sep(self.global_saltenv[tgt_env][name]) else: return strip_sep(getattr(self, '_' + name)) setattr(cls, name, _getconf)
[ "def", "add_conf_overlay", "(", "cls", ",", "name", ")", ":", "def", "_getconf", "(", "self", ",", "tgt_env", "=", "'base'", ")", ":", "strip_sep", "=", "lambda", "x", ":", "x", ".", "rstrip", "(", "os", ".", "sep", ")", "if", "name", "in", "(", ...
Programmatically determine config value based on the desired saltenv
[ "Programmatically", "determine", "config", "value", "based", "on", "the", "desired", "saltenv" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L509-L570
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.check_root
def check_root(self): ''' Check if the relative root path exists in the checked-out copy of the remote. Return the full path to that relative root if it does exist, otherwise return None. ''' # No need to pass an environment to self.root() here since per-saltenv # configuration is a gitfs-only feature and check_root() is not used # for gitfs. root_dir = salt.utils.path.join(self.cachedir, self.root()).rstrip(os.sep) if os.path.isdir(root_dir): return root_dir log.error( 'Root path \'%s\' not present in %s remote \'%s\', ' 'skipping.', self.root(), self.role, self.id ) return None
python
def check_root(self): ''' Check if the relative root path exists in the checked-out copy of the remote. Return the full path to that relative root if it does exist, otherwise return None. ''' # No need to pass an environment to self.root() here since per-saltenv # configuration is a gitfs-only feature and check_root() is not used # for gitfs. root_dir = salt.utils.path.join(self.cachedir, self.root()).rstrip(os.sep) if os.path.isdir(root_dir): return root_dir log.error( 'Root path \'%s\' not present in %s remote \'%s\', ' 'skipping.', self.root(), self.role, self.id ) return None
[ "def", "check_root", "(", "self", ")", ":", "# No need to pass an environment to self.root() here since per-saltenv", "# configuration is a gitfs-only feature and check_root() is not used", "# for gitfs.", "root_dir", "=", "salt", ".", "utils", ".", "path", ".", "join", "(", "s...
Check if the relative root path exists in the checked-out copy of the remote. Return the full path to that relative root if it does exist, otherwise return None.
[ "Check", "if", "the", "relative", "root", "path", "exists", "in", "the", "checked", "-", "out", "copy", "of", "the", "remote", ".", "Return", "the", "full", "path", "to", "that", "relative", "root", "if", "it", "does", "exist", "otherwise", "return", "No...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L572-L588
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.clean_stale_refs
def clean_stale_refs(self): ''' Remove stale refs so that they are no longer seen as fileserver envs ''' cleaned = [] cmd_str = 'git remote prune origin' # Attempt to force all output to plain ascii english, which is what some parsing code # may expect. # According to stackoverflow (http://goo.gl/l74GC8), we are setting LANGUAGE as well # just to be sure. env = os.environ.copy() env[b"LANGUAGE"] = b"C" env[b"LC_ALL"] = b"C" cmd = subprocess.Popen( shlex.split(cmd_str), close_fds=not salt.utils.platform.is_windows(), cwd=os.path.dirname(self.gitdir), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = cmd.communicate()[0] if six.PY3: output = output.decode(__salt_system_encoding__) if cmd.returncode != 0: log.warning( 'Failed to prune stale branches for %s remote \'%s\'. ' 'Output from \'%s\' follows:\n%s', self.role, self.id, cmd_str, output ) else: marker = ' * [pruned] ' for line in salt.utils.itertools.split(output, '\n'): if line.startswith(marker): cleaned.append(line[len(marker):].strip()) if cleaned: log.debug( '%s pruned the following stale refs: %s', self.role, ', '.join(cleaned) ) return cleaned
python
def clean_stale_refs(self): ''' Remove stale refs so that they are no longer seen as fileserver envs ''' cleaned = [] cmd_str = 'git remote prune origin' # Attempt to force all output to plain ascii english, which is what some parsing code # may expect. # According to stackoverflow (http://goo.gl/l74GC8), we are setting LANGUAGE as well # just to be sure. env = os.environ.copy() env[b"LANGUAGE"] = b"C" env[b"LC_ALL"] = b"C" cmd = subprocess.Popen( shlex.split(cmd_str), close_fds=not salt.utils.platform.is_windows(), cwd=os.path.dirname(self.gitdir), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = cmd.communicate()[0] if six.PY3: output = output.decode(__salt_system_encoding__) if cmd.returncode != 0: log.warning( 'Failed to prune stale branches for %s remote \'%s\'. ' 'Output from \'%s\' follows:\n%s', self.role, self.id, cmd_str, output ) else: marker = ' * [pruned] ' for line in salt.utils.itertools.split(output, '\n'): if line.startswith(marker): cleaned.append(line[len(marker):].strip()) if cleaned: log.debug( '%s pruned the following stale refs: %s', self.role, ', '.join(cleaned) ) return cleaned
[ "def", "clean_stale_refs", "(", "self", ")", ":", "cleaned", "=", "[", "]", "cmd_str", "=", "'git remote prune origin'", "# Attempt to force all output to plain ascii english, which is what some parsing code", "# may expect.", "# According to stackoverflow (http://goo.gl/l74GC8), we ar...
Remove stale refs so that they are no longer seen as fileserver envs
[ "Remove", "stale", "refs", "so", "that", "they", "are", "no", "longer", "seen", "as", "fileserver", "envs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L590-L631
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.clear_lock
def clear_lock(self, lock_type='update'): ''' Clear update.lk ''' lock_file = self._get_lock_file(lock_type=lock_type) def _add_error(errlist, exc): msg = ('Unable to remove update lock for {0} ({1}): {2} ' .format(self.url, lock_file, exc)) log.debug(msg) errlist.append(msg) success = [] failed = [] try: os.remove(lock_file) except OSError as exc: if exc.errno == errno.ENOENT: # No lock file present pass elif exc.errno == errno.EISDIR: # Somehow this path is a directory. Should never happen # unless some wiseguy manually creates a directory at this # path, but just in case, handle it. try: shutil.rmtree(lock_file) except OSError as exc: _add_error(failed, exc) else: _add_error(failed, exc) else: msg = 'Removed {0} lock for {1} remote \'{2}\''.format( lock_type, self.role, self.id ) log.debug(msg) success.append(msg) return success, failed
python
def clear_lock(self, lock_type='update'): ''' Clear update.lk ''' lock_file = self._get_lock_file(lock_type=lock_type) def _add_error(errlist, exc): msg = ('Unable to remove update lock for {0} ({1}): {2} ' .format(self.url, lock_file, exc)) log.debug(msg) errlist.append(msg) success = [] failed = [] try: os.remove(lock_file) except OSError as exc: if exc.errno == errno.ENOENT: # No lock file present pass elif exc.errno == errno.EISDIR: # Somehow this path is a directory. Should never happen # unless some wiseguy manually creates a directory at this # path, but just in case, handle it. try: shutil.rmtree(lock_file) except OSError as exc: _add_error(failed, exc) else: _add_error(failed, exc) else: msg = 'Removed {0} lock for {1} remote \'{2}\''.format( lock_type, self.role, self.id ) log.debug(msg) success.append(msg) return success, failed
[ "def", "clear_lock", "(", "self", ",", "lock_type", "=", "'update'", ")", ":", "lock_file", "=", "self", ".", "_get_lock_file", "(", "lock_type", "=", "lock_type", ")", "def", "_add_error", "(", "errlist", ",", "exc", ")", ":", "msg", "=", "(", "'Unable ...
Clear update.lk
[ "Clear", "update", ".", "lk" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L633-L672
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.enforce_git_config
def enforce_git_config(self): ''' For the config options which need to be maintained in the git config, ensure that the git config file is configured as desired. ''' git_config = os.path.join(self.gitdir, 'config') conf = salt.utils.configparser.GitConfigParser() if not conf.read(git_config): log.error('Failed to read from git config file %s', git_config) else: # We are currently enforcing the following git config items: # 1. Fetch URL # 2. refspecs used in fetch # 3. http.sslVerify conf_changed = False remote_section = 'remote "origin"' # 1. URL try: url = conf.get(remote_section, 'url') except salt.utils.configparser.NoSectionError: # First time we've init'ed this repo, we need to add the # section for the remote to the git config conf.add_section(remote_section) conf_changed = True url = None log.debug( 'Current fetch URL for %s remote \'%s\': %s (desired: %s)', self.role, self.id, url, self.url ) if url != self.url: conf.set(remote_section, 'url', self.url) log.debug( 'Fetch URL for %s remote \'%s\' set to %s', self.role, self.id, self.url ) conf_changed = True # 2. refspecs try: refspecs = sorted( conf.get(remote_section, 'fetch', as_list=True)) except salt.utils.configparser.NoOptionError: # No 'fetch' option present in the remote section. Should never # happen, but if it does for some reason, don't let it cause a # traceback. refspecs = [] desired_refspecs = sorted(self.refspecs) log.debug( 'Current refspecs for %s remote \'%s\': %s (desired: %s)', self.role, self.id, refspecs, desired_refspecs ) if refspecs != desired_refspecs: conf.set_multivar(remote_section, 'fetch', self.refspecs) log.debug( 'Refspecs for %s remote \'%s\' set to %s', self.role, self.id, desired_refspecs ) conf_changed = True # 3. http.sslVerify try: ssl_verify = conf.get('http', 'sslVerify') except salt.utils.configparser.NoSectionError: conf.add_section('http') ssl_verify = None except salt.utils.configparser.NoOptionError: ssl_verify = None desired_ssl_verify = six.text_type(self.ssl_verify).lower() log.debug( 'Current http.sslVerify for %s remote \'%s\': %s (desired: %s)', self.role, self.id, ssl_verify, desired_ssl_verify ) if ssl_verify != desired_ssl_verify: conf.set('http', 'sslVerify', desired_ssl_verify) log.debug( 'http.sslVerify for %s remote \'%s\' set to %s', self.role, self.id, desired_ssl_verify ) conf_changed = True # Write changes, if necessary if conf_changed: with salt.utils.files.fopen(git_config, 'w') as fp_: conf.write(fp_) log.debug( 'Config updates for %s remote \'%s\' written to %s', self.role, self.id, git_config )
python
def enforce_git_config(self): ''' For the config options which need to be maintained in the git config, ensure that the git config file is configured as desired. ''' git_config = os.path.join(self.gitdir, 'config') conf = salt.utils.configparser.GitConfigParser() if not conf.read(git_config): log.error('Failed to read from git config file %s', git_config) else: # We are currently enforcing the following git config items: # 1. Fetch URL # 2. refspecs used in fetch # 3. http.sslVerify conf_changed = False remote_section = 'remote "origin"' # 1. URL try: url = conf.get(remote_section, 'url') except salt.utils.configparser.NoSectionError: # First time we've init'ed this repo, we need to add the # section for the remote to the git config conf.add_section(remote_section) conf_changed = True url = None log.debug( 'Current fetch URL for %s remote \'%s\': %s (desired: %s)', self.role, self.id, url, self.url ) if url != self.url: conf.set(remote_section, 'url', self.url) log.debug( 'Fetch URL for %s remote \'%s\' set to %s', self.role, self.id, self.url ) conf_changed = True # 2. refspecs try: refspecs = sorted( conf.get(remote_section, 'fetch', as_list=True)) except salt.utils.configparser.NoOptionError: # No 'fetch' option present in the remote section. Should never # happen, but if it does for some reason, don't let it cause a # traceback. refspecs = [] desired_refspecs = sorted(self.refspecs) log.debug( 'Current refspecs for %s remote \'%s\': %s (desired: %s)', self.role, self.id, refspecs, desired_refspecs ) if refspecs != desired_refspecs: conf.set_multivar(remote_section, 'fetch', self.refspecs) log.debug( 'Refspecs for %s remote \'%s\' set to %s', self.role, self.id, desired_refspecs ) conf_changed = True # 3. http.sslVerify try: ssl_verify = conf.get('http', 'sslVerify') except salt.utils.configparser.NoSectionError: conf.add_section('http') ssl_verify = None except salt.utils.configparser.NoOptionError: ssl_verify = None desired_ssl_verify = six.text_type(self.ssl_verify).lower() log.debug( 'Current http.sslVerify for %s remote \'%s\': %s (desired: %s)', self.role, self.id, ssl_verify, desired_ssl_verify ) if ssl_verify != desired_ssl_verify: conf.set('http', 'sslVerify', desired_ssl_verify) log.debug( 'http.sslVerify for %s remote \'%s\' set to %s', self.role, self.id, desired_ssl_verify ) conf_changed = True # Write changes, if necessary if conf_changed: with salt.utils.files.fopen(git_config, 'w') as fp_: conf.write(fp_) log.debug( 'Config updates for %s remote \'%s\' written to %s', self.role, self.id, git_config )
[ "def", "enforce_git_config", "(", "self", ")", ":", "git_config", "=", "os", ".", "path", ".", "join", "(", "self", ".", "gitdir", ",", "'config'", ")", "conf", "=", "salt", ".", "utils", ".", "configparser", ".", "GitConfigParser", "(", ")", "if", "no...
For the config options which need to be maintained in the git config, ensure that the git config file is configured as desired.
[ "For", "the", "config", "options", "which", "need", "to", "be", "maintained", "in", "the", "git", "config", "ensure", "that", "the", "git", "config", "file", "is", "configured", "as", "desired", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L674-L762
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.fetch
def fetch(self): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. This function requires that a _fetch() function be implemented in a sub-class. ''' try: with self.gen_lock(lock_type='update'): log.debug('Fetching %s remote \'%s\'', self.role, self.id) # Run provider-specific fetch code return self._fetch() except GitLockError as exc: if exc.errno == errno.EEXIST: log.warning( 'Update lock file is present for %s remote \'%s\', ' 'skipping. If this warning persists, it is possible that ' 'the update process was interrupted, but the lock could ' 'also have been manually set. Removing %s or running ' '\'salt-run cache.clear_git_lock %s type=update\' will ' 'allow updates to continue for this remote.', self.role, self.id, self._get_lock_file(lock_type='update'), self.role, ) return False
python
def fetch(self): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. This function requires that a _fetch() function be implemented in a sub-class. ''' try: with self.gen_lock(lock_type='update'): log.debug('Fetching %s remote \'%s\'', self.role, self.id) # Run provider-specific fetch code return self._fetch() except GitLockError as exc: if exc.errno == errno.EEXIST: log.warning( 'Update lock file is present for %s remote \'%s\', ' 'skipping. If this warning persists, it is possible that ' 'the update process was interrupted, but the lock could ' 'also have been manually set. Removing %s or running ' '\'salt-run cache.clear_git_lock %s type=update\' will ' 'allow updates to continue for this remote.', self.role, self.id, self._get_lock_file(lock_type='update'), self.role, ) return False
[ "def", "fetch", "(", "self", ")", ":", "try", ":", "with", "self", ".", "gen_lock", "(", "lock_type", "=", "'update'", ")", ":", "log", ".", "debug", "(", "'Fetching %s remote \\'%s\\''", ",", "self", ".", "role", ",", "self", ".", "id", ")", "# Run pr...
Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. This function requires that a _fetch() function be implemented in a sub-class.
[ "Fetch", "the", "repo", ".", "If", "the", "local", "copy", "was", "updated", "return", "True", ".", "If", "the", "local", "copy", "was", "already", "up", "-", "to", "-", "date", "return", "False", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L764-L791
train
saltstack/salt
salt/utils/gitfs.py
GitProvider._lock
def _lock(self, lock_type='update', failhard=False): ''' Place a lock file if (and only if) it does not already exist. ''' try: fh_ = os.open(self._get_lock_file(lock_type), os.O_CREAT | os.O_EXCL | os.O_WRONLY) with os.fdopen(fh_, 'wb'): # Write the lock file and close the filehandle os.write(fh_, salt.utils.stringutils.to_bytes(six.text_type(os.getpid()))) except (OSError, IOError) as exc: if exc.errno == errno.EEXIST: with salt.utils.files.fopen(self._get_lock_file(lock_type), 'r') as fd_: try: pid = int(salt.utils.stringutils.to_unicode(fd_.readline()).rstrip()) except ValueError: # Lock file is empty, set pid to 0 so it evaluates as # False. pid = 0 global_lock_key = self.role + '_global_lock' lock_file = self._get_lock_file(lock_type=lock_type) if self.opts[global_lock_key]: msg = ( '{0} is enabled and {1} lockfile {2} is present for ' '{3} remote \'{4}\'.'.format( global_lock_key, lock_type, lock_file, self.role, self.id, ) ) if pid: msg += ' Process {0} obtained the lock'.format(pid) if not pid_exists(pid): msg += (' but this process is not running. The ' 'update may have been interrupted. If ' 'using multi-master with shared gitfs ' 'cache, the lock may have been obtained ' 'by another master.') log.warning(msg) if failhard: raise exc return elif pid and pid_exists(pid): log.warning('Process %d has a %s %s lock (%s)', pid, self.role, lock_type, lock_file) if failhard: raise return else: if pid: log.warning( 'Process %d has a %s %s lock (%s), but this ' 'process is not running. Cleaning up lock file.', pid, self.role, lock_type, lock_file ) success, fail = self.clear_lock() if success: return self._lock(lock_type='update', failhard=failhard) elif failhard: raise return else: msg = 'Unable to set {0} lock for {1} ({2}): {3} '.format( lock_type, self.id, self._get_lock_file(lock_type), exc ) log.error(msg, exc_info=True) raise GitLockError(exc.errno, msg) msg = 'Set {0} lock for {1} remote \'{2}\''.format( lock_type, self.role, self.id ) log.debug(msg) return msg
python
def _lock(self, lock_type='update', failhard=False): ''' Place a lock file if (and only if) it does not already exist. ''' try: fh_ = os.open(self._get_lock_file(lock_type), os.O_CREAT | os.O_EXCL | os.O_WRONLY) with os.fdopen(fh_, 'wb'): # Write the lock file and close the filehandle os.write(fh_, salt.utils.stringutils.to_bytes(six.text_type(os.getpid()))) except (OSError, IOError) as exc: if exc.errno == errno.EEXIST: with salt.utils.files.fopen(self._get_lock_file(lock_type), 'r') as fd_: try: pid = int(salt.utils.stringutils.to_unicode(fd_.readline()).rstrip()) except ValueError: # Lock file is empty, set pid to 0 so it evaluates as # False. pid = 0 global_lock_key = self.role + '_global_lock' lock_file = self._get_lock_file(lock_type=lock_type) if self.opts[global_lock_key]: msg = ( '{0} is enabled and {1} lockfile {2} is present for ' '{3} remote \'{4}\'.'.format( global_lock_key, lock_type, lock_file, self.role, self.id, ) ) if pid: msg += ' Process {0} obtained the lock'.format(pid) if not pid_exists(pid): msg += (' but this process is not running. The ' 'update may have been interrupted. If ' 'using multi-master with shared gitfs ' 'cache, the lock may have been obtained ' 'by another master.') log.warning(msg) if failhard: raise exc return elif pid and pid_exists(pid): log.warning('Process %d has a %s %s lock (%s)', pid, self.role, lock_type, lock_file) if failhard: raise return else: if pid: log.warning( 'Process %d has a %s %s lock (%s), but this ' 'process is not running. Cleaning up lock file.', pid, self.role, lock_type, lock_file ) success, fail = self.clear_lock() if success: return self._lock(lock_type='update', failhard=failhard) elif failhard: raise return else: msg = 'Unable to set {0} lock for {1} ({2}): {3} '.format( lock_type, self.id, self._get_lock_file(lock_type), exc ) log.error(msg, exc_info=True) raise GitLockError(exc.errno, msg) msg = 'Set {0} lock for {1} remote \'{2}\''.format( lock_type, self.role, self.id ) log.debug(msg) return msg
[ "def", "_lock", "(", "self", ",", "lock_type", "=", "'update'", ",", "failhard", "=", "False", ")", ":", "try", ":", "fh_", "=", "os", ".", "open", "(", "self", ".", "_get_lock_file", "(", "lock_type", ")", ",", "os", ".", "O_CREAT", "|", "os", "."...
Place a lock file if (and only if) it does not already exist.
[ "Place", "a", "lock", "file", "if", "(", "and", "only", "if", ")", "it", "does", "not", "already", "exist", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L793-L872
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.lock
def lock(self): ''' Place an lock file and report on the success/failure. This is an interface to be used by the fileserver runner, so it is hard-coded to perform an update lock. We aren't using the gen_lock() contextmanager here because the lock is meant to stay and not be automatically removed. ''' success = [] failed = [] try: result = self._lock(lock_type='update') except GitLockError as exc: failed.append(exc.strerror) else: if result is not None: success.append(result) return success, failed
python
def lock(self): ''' Place an lock file and report on the success/failure. This is an interface to be used by the fileserver runner, so it is hard-coded to perform an update lock. We aren't using the gen_lock() contextmanager here because the lock is meant to stay and not be automatically removed. ''' success = [] failed = [] try: result = self._lock(lock_type='update') except GitLockError as exc: failed.append(exc.strerror) else: if result is not None: success.append(result) return success, failed
[ "def", "lock", "(", "self", ")", ":", "success", "=", "[", "]", "failed", "=", "[", "]", "try", ":", "result", "=", "self", ".", "_lock", "(", "lock_type", "=", "'update'", ")", "except", "GitLockError", "as", "exc", ":", "failed", ".", "append", "...
Place an lock file and report on the success/failure. This is an interface to be used by the fileserver runner, so it is hard-coded to perform an update lock. We aren't using the gen_lock() contextmanager here because the lock is meant to stay and not be automatically removed.
[ "Place", "an", "lock", "file", "and", "report", "on", "the", "success", "/", "failure", ".", "This", "is", "an", "interface", "to", "be", "used", "by", "the", "fileserver", "runner", "so", "it", "is", "hard", "-", "coded", "to", "perform", "an", "updat...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L874-L891
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.gen_lock
def gen_lock(self, lock_type='update', timeout=0, poll_interval=0.5): ''' Set and automatically clear a lock ''' if not isinstance(lock_type, six.string_types): raise GitLockError( errno.EINVAL, 'Invalid lock_type \'{0}\''.format(lock_type) ) # Make sure that we have a positive integer timeout, otherwise just set # it to zero. try: timeout = int(timeout) except ValueError: timeout = 0 else: if timeout < 0: timeout = 0 if not isinstance(poll_interval, (six.integer_types, float)) \ or poll_interval < 0: poll_interval = 0.5 if poll_interval > timeout: poll_interval = timeout lock_set = False try: time_start = time.time() while True: try: self._lock(lock_type=lock_type, failhard=True) lock_set = True yield # Break out of his loop once we've yielded the lock, to # avoid continued attempts to iterate and establish lock break except (OSError, IOError, GitLockError) as exc: if not timeout or time.time() - time_start > timeout: raise GitLockError(exc.errno, exc.strerror) else: log.debug( 'A %s lock is already present for %s remote ' '\'%s\', sleeping %f second(s)', lock_type, self.role, self.id, poll_interval ) time.sleep(poll_interval) continue finally: if lock_set: self.clear_lock(lock_type=lock_type)
python
def gen_lock(self, lock_type='update', timeout=0, poll_interval=0.5): ''' Set and automatically clear a lock ''' if not isinstance(lock_type, six.string_types): raise GitLockError( errno.EINVAL, 'Invalid lock_type \'{0}\''.format(lock_type) ) # Make sure that we have a positive integer timeout, otherwise just set # it to zero. try: timeout = int(timeout) except ValueError: timeout = 0 else: if timeout < 0: timeout = 0 if not isinstance(poll_interval, (six.integer_types, float)) \ or poll_interval < 0: poll_interval = 0.5 if poll_interval > timeout: poll_interval = timeout lock_set = False try: time_start = time.time() while True: try: self._lock(lock_type=lock_type, failhard=True) lock_set = True yield # Break out of his loop once we've yielded the lock, to # avoid continued attempts to iterate and establish lock break except (OSError, IOError, GitLockError) as exc: if not timeout or time.time() - time_start > timeout: raise GitLockError(exc.errno, exc.strerror) else: log.debug( 'A %s lock is already present for %s remote ' '\'%s\', sleeping %f second(s)', lock_type, self.role, self.id, poll_interval ) time.sleep(poll_interval) continue finally: if lock_set: self.clear_lock(lock_type=lock_type)
[ "def", "gen_lock", "(", "self", ",", "lock_type", "=", "'update'", ",", "timeout", "=", "0", ",", "poll_interval", "=", "0.5", ")", ":", "if", "not", "isinstance", "(", "lock_type", ",", "six", ".", "string_types", ")", ":", "raise", "GitLockError", "(",...
Set and automatically clear a lock
[ "Set", "and", "automatically", "clear", "a", "lock" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L894-L945
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.env_is_exposed
def env_is_exposed(self, tgt_env): ''' Check if an environment is exposed by comparing it against a whitelist and blacklist. ''' return salt.utils.stringutils.check_whitelist_blacklist( tgt_env, whitelist=self.saltenv_whitelist, blacklist=self.saltenv_blacklist, )
python
def env_is_exposed(self, tgt_env): ''' Check if an environment is exposed by comparing it against a whitelist and blacklist. ''' return salt.utils.stringutils.check_whitelist_blacklist( tgt_env, whitelist=self.saltenv_whitelist, blacklist=self.saltenv_blacklist, )
[ "def", "env_is_exposed", "(", "self", ",", "tgt_env", ")", ":", "return", "salt", ".", "utils", ".", "stringutils", ".", "check_whitelist_blacklist", "(", "tgt_env", ",", "whitelist", "=", "self", ".", "saltenv_whitelist", ",", "blacklist", "=", "self", ".", ...
Check if an environment is exposed by comparing it against a whitelist and blacklist.
[ "Check", "if", "an", "environment", "is", "exposed", "by", "comparing", "it", "against", "a", "whitelist", "and", "blacklist", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L965-L974
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.get_checkout_target
def get_checkout_target(self): ''' Resolve dynamically-set branch ''' if self.role == 'git_pillar' and self.branch == '__env__': try: return self.all_saltenvs except AttributeError: # all_saltenvs not configured for this remote pass target = self.opts.get('pillarenv') \ or self.opts.get('saltenv') \ or 'base' return self.base \ if target == 'base' \ else six.text_type(target) return self.branch
python
def get_checkout_target(self): ''' Resolve dynamically-set branch ''' if self.role == 'git_pillar' and self.branch == '__env__': try: return self.all_saltenvs except AttributeError: # all_saltenvs not configured for this remote pass target = self.opts.get('pillarenv') \ or self.opts.get('saltenv') \ or 'base' return self.base \ if target == 'base' \ else six.text_type(target) return self.branch
[ "def", "get_checkout_target", "(", "self", ")", ":", "if", "self", ".", "role", "==", "'git_pillar'", "and", "self", ".", "branch", "==", "'__env__'", ":", "try", ":", "return", "self", ".", "all_saltenvs", "except", "AttributeError", ":", "# all_saltenvs not ...
Resolve dynamically-set branch
[ "Resolve", "dynamically", "-", "set", "branch" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L1001-L1017
train
saltstack/salt
salt/utils/gitfs.py
GitProvider.get_tree
def get_tree(self, tgt_env): ''' Return a tree object for the specified environment ''' if not self.env_is_exposed(tgt_env): return None tgt_ref = self.ref(tgt_env) if tgt_ref is None: return None for ref_type in self.ref_types: try: func_name = 'get_tree_from_{0}'.format(ref_type) func = getattr(self, func_name) except AttributeError: log.error( '%s class is missing function \'%s\'', self.__class__.__name__, func_name ) else: candidate = func(tgt_ref) if candidate is not None: return candidate # No matches found return None
python
def get_tree(self, tgt_env): ''' Return a tree object for the specified environment ''' if not self.env_is_exposed(tgt_env): return None tgt_ref = self.ref(tgt_env) if tgt_ref is None: return None for ref_type in self.ref_types: try: func_name = 'get_tree_from_{0}'.format(ref_type) func = getattr(self, func_name) except AttributeError: log.error( '%s class is missing function \'%s\'', self.__class__.__name__, func_name ) else: candidate = func(tgt_ref) if candidate is not None: return candidate # No matches found return None
[ "def", "get_tree", "(", "self", ",", "tgt_env", ")", ":", "if", "not", "self", ".", "env_is_exposed", "(", "tgt_env", ")", ":", "return", "None", "tgt_ref", "=", "self", ".", "ref", "(", "tgt_env", ")", "if", "tgt_ref", "is", "None", ":", "return", "...
Return a tree object for the specified environment
[ "Return", "a", "tree", "object", "for", "the", "specified", "environment" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L1019-L1045
train