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/utils/url.py
split_env
def split_env(url): ''' remove the saltenv query parameter from a 'salt://' url ''' if not url.startswith('salt://'): return url, None path, senv = parse(url) return create(path), senv
python
def split_env(url): ''' remove the saltenv query parameter from a 'salt://' url ''' if not url.startswith('salt://'): return url, None path, senv = parse(url) return create(path), senv
[ "def", "split_env", "(", "url", ")", ":", "if", "not", "url", ".", "startswith", "(", "'salt://'", ")", ":", "return", "url", ",", "None", "path", ",", "senv", "=", "parse", "(", "url", ")", "return", "create", "(", "path", ")", ",", "senv" ]
remove the saltenv query parameter from a 'salt://' url
[ "remove", "the", "saltenv", "query", "parameter", "from", "a", "salt", ":", "//", "url" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L124-L132
train
saltstack/salt
salt/utils/url.py
add_http_basic_auth
def add_http_basic_auth(url, user=None, password=None, https_only=False): ''' Return a string with http basic auth incorporated into it ''' if user is None and password is None: return url else: urltuple = urlparse(url) if https_only and urltuple.scheme != 'https': raise ValueError('Basic Auth only supported for HTTPS') if password is None: netloc = '{0}@{1}'.format( user, urltuple.netloc ) urltuple = urltuple._replace(netloc=netloc) return urlunparse(urltuple) else: netloc = '{0}:{1}@{2}'.format( user, password, urltuple.netloc ) urltuple = urltuple._replace(netloc=netloc) return urlunparse(urltuple)
python
def add_http_basic_auth(url, user=None, password=None, https_only=False): ''' Return a string with http basic auth incorporated into it ''' if user is None and password is None: return url else: urltuple = urlparse(url) if https_only and urltuple.scheme != 'https': raise ValueError('Basic Auth only supported for HTTPS') if password is None: netloc = '{0}@{1}'.format( user, urltuple.netloc ) urltuple = urltuple._replace(netloc=netloc) return urlunparse(urltuple) else: netloc = '{0}:{1}@{2}'.format( user, password, urltuple.netloc ) urltuple = urltuple._replace(netloc=netloc) return urlunparse(urltuple)
[ "def", "add_http_basic_auth", "(", "url", ",", "user", "=", "None", ",", "password", "=", "None", ",", "https_only", "=", "False", ")", ":", "if", "user", "is", "None", "and", "password", "is", "None", ":", "return", "url", "else", ":", "urltuple", "="...
Return a string with http basic auth incorporated into it
[ "Return", "a", "string", "with", "http", "basic", "auth", "incorporated", "into", "it" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L152-L179
train
saltstack/salt
salt/utils/url.py
redact_http_basic_auth
def redact_http_basic_auth(output): ''' Remove HTTP user and password ''' # We can't use re.compile because re.compile(someregex).sub() doesn't # support flags even in Python 2.7. url_re = '(https?)://.*@' redacted = r'\1://<redacted>@' if sys.version_info >= (2, 7): # re.sub() supports flags as of 2.7, use this to do a case-insensitive # match. return re.sub(url_re, redacted, output, flags=re.IGNORECASE) else: # We're on python 2.6, test if a lowercased version of the output # string matches the regex... if re.search(url_re, output.lower()): # ... and if it does, perform the regex substitution. return re.sub(url_re, redacted, output.lower()) # No match, just return the original string return output
python
def redact_http_basic_auth(output): ''' Remove HTTP user and password ''' # We can't use re.compile because re.compile(someregex).sub() doesn't # support flags even in Python 2.7. url_re = '(https?)://.*@' redacted = r'\1://<redacted>@' if sys.version_info >= (2, 7): # re.sub() supports flags as of 2.7, use this to do a case-insensitive # match. return re.sub(url_re, redacted, output, flags=re.IGNORECASE) else: # We're on python 2.6, test if a lowercased version of the output # string matches the regex... if re.search(url_re, output.lower()): # ... and if it does, perform the regex substitution. return re.sub(url_re, redacted, output.lower()) # No match, just return the original string return output
[ "def", "redact_http_basic_auth", "(", "output", ")", ":", "# We can't use re.compile because re.compile(someregex).sub() doesn't", "# support flags even in Python 2.7.", "url_re", "=", "'(https?)://.*@'", "redacted", "=", "r'\\1://<redacted>@'", "if", "sys", ".", "version_info", ...
Remove HTTP user and password
[ "Remove", "HTTP", "user", "and", "password" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L182-L201
train
saltstack/salt
salt/modules/yumpkg.py
_get_hold
def _get_hold(line, pattern=__HOLD_PATTERN, full=True): ''' Resolve a package name from a line containing the hold expression. If the regex is not matched, None is returned. yum ==> 2:vim-enhanced-7.4.629-5.el6.* dnf ==> vim-enhanced-2:7.4.827-1.fc22.* ''' if full: if _yum() == 'dnf': lock_re = r'({0}-\S+)'.format(pattern) else: lock_re = r'(\d+:{0}-\S+)'.format(pattern) else: if _yum() == 'dnf': lock_re = r'({0}-\S+)'.format(pattern) else: lock_re = r'\d+:({0}-\S+)'.format(pattern) match = re.search(lock_re, line) if match: if not full: woarch = match.group(1).rsplit('.', 1)[0] worel = woarch.rsplit('-', 1)[0] return worel.rsplit('-', 1)[0] else: return match.group(1) return None
python
def _get_hold(line, pattern=__HOLD_PATTERN, full=True): ''' Resolve a package name from a line containing the hold expression. If the regex is not matched, None is returned. yum ==> 2:vim-enhanced-7.4.629-5.el6.* dnf ==> vim-enhanced-2:7.4.827-1.fc22.* ''' if full: if _yum() == 'dnf': lock_re = r'({0}-\S+)'.format(pattern) else: lock_re = r'(\d+:{0}-\S+)'.format(pattern) else: if _yum() == 'dnf': lock_re = r'({0}-\S+)'.format(pattern) else: lock_re = r'\d+:({0}-\S+)'.format(pattern) match = re.search(lock_re, line) if match: if not full: woarch = match.group(1).rsplit('.', 1)[0] worel = woarch.rsplit('-', 1)[0] return worel.rsplit('-', 1)[0] else: return match.group(1) return None
[ "def", "_get_hold", "(", "line", ",", "pattern", "=", "__HOLD_PATTERN", ",", "full", "=", "True", ")", ":", "if", "full", ":", "if", "_yum", "(", ")", "==", "'dnf'", ":", "lock_re", "=", "r'({0}-\\S+)'", ".", "format", "(", "pattern", ")", "else", ":...
Resolve a package name from a line containing the hold expression. If the regex is not matched, None is returned. yum ==> 2:vim-enhanced-7.4.629-5.el6.* dnf ==> vim-enhanced-2:7.4.827-1.fc22.*
[ "Resolve", "a", "package", "name", "from", "a", "line", "containing", "the", "hold", "expression", ".", "If", "the", "regex", "is", "not", "matched", "None", "is", "returned", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L109-L136
train
saltstack/salt
salt/modules/yumpkg.py
_yum
def _yum(): ''' Determine package manager name (yum or dnf), depending on the system version. ''' contextkey = 'yum_bin' if contextkey not in __context__: if ('fedora' in __grains__['os'].lower() and int(__grains__['osrelease']) >= 22): __context__[contextkey] = 'dnf' elif 'photon' in __grains__['os'].lower(): __context__[contextkey] = 'tdnf' else: __context__[contextkey] = 'yum' return __context__[contextkey]
python
def _yum(): ''' Determine package manager name (yum or dnf), depending on the system version. ''' contextkey = 'yum_bin' if contextkey not in __context__: if ('fedora' in __grains__['os'].lower() and int(__grains__['osrelease']) >= 22): __context__[contextkey] = 'dnf' elif 'photon' in __grains__['os'].lower(): __context__[contextkey] = 'tdnf' else: __context__[contextkey] = 'yum' return __context__[contextkey]
[ "def", "_yum", "(", ")", ":", "contextkey", "=", "'yum_bin'", "if", "contextkey", "not", "in", "__context__", ":", "if", "(", "'fedora'", "in", "__grains__", "[", "'os'", "]", ".", "lower", "(", ")", "and", "int", "(", "__grains__", "[", "'osrelease'", ...
Determine package manager name (yum or dnf), depending on the system version.
[ "Determine", "package", "manager", "name", "(", "yum", "or", "dnf", ")", "depending", "on", "the", "system", "version", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L139-L153
train
saltstack/salt
salt/modules/yumpkg.py
_call_yum
def _call_yum(args, **kwargs): ''' Call yum/dnf. ''' params = {'output_loglevel': 'trace', 'python_shell': False, 'env': salt.utils.environment.get_module_environment(globals())} params.update(kwargs) cmd = [] if salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.append(_yum()) cmd.extend(args) return __salt__['cmd.run_all'](cmd, **params)
python
def _call_yum(args, **kwargs): ''' Call yum/dnf. ''' params = {'output_loglevel': 'trace', 'python_shell': False, 'env': salt.utils.environment.get_module_environment(globals())} params.update(kwargs) cmd = [] if salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.append(_yum()) cmd.extend(args) return __salt__['cmd.run_all'](cmd, **params)
[ "def", "_call_yum", "(", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'output_loglevel'", ":", "'trace'", ",", "'python_shell'", ":", "False", ",", "'env'", ":", "salt", ".", "utils", ".", "environment", ".", "get_module_environment", "(...
Call yum/dnf.
[ "Call", "yum", "/", "dnf", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L156-L170
train
saltstack/salt
salt/modules/yumpkg.py
_yum_pkginfo
def _yum_pkginfo(output): ''' Parse yum/dnf output (which could contain irregular line breaks if package names are long) retrieving the name, version, etc., and return a list of pkginfo namedtuples. ''' cur = {} keys = itertools.cycle(('name', 'version', 'repoid')) values = salt.utils.itertools.split(_strip_headers(output)) osarch = __grains__['osarch'] for (key, value) in zip(keys, values): if key == 'name': try: cur['name'], cur['arch'] = value.rsplit('.', 1) except ValueError: cur['name'] = value cur['arch'] = osarch cur['name'] = salt.utils.pkg.rpm.resolve_name(cur['name'], cur['arch'], osarch) else: if key == 'version': # Suppport packages with no 'Release' parameter value = value.rstrip('-') elif key == 'repoid': # Installed packages show a '@' at the beginning value = value.lstrip('@') cur[key] = value if key == 'repoid': # We're done with this package, create the pkginfo namedtuple pkginfo = salt.utils.pkg.rpm.pkginfo(**cur) # Clear the dict for the next package cur = {} # Yield the namedtuple if pkginfo is not None: yield pkginfo
python
def _yum_pkginfo(output): ''' Parse yum/dnf output (which could contain irregular line breaks if package names are long) retrieving the name, version, etc., and return a list of pkginfo namedtuples. ''' cur = {} keys = itertools.cycle(('name', 'version', 'repoid')) values = salt.utils.itertools.split(_strip_headers(output)) osarch = __grains__['osarch'] for (key, value) in zip(keys, values): if key == 'name': try: cur['name'], cur['arch'] = value.rsplit('.', 1) except ValueError: cur['name'] = value cur['arch'] = osarch cur['name'] = salt.utils.pkg.rpm.resolve_name(cur['name'], cur['arch'], osarch) else: if key == 'version': # Suppport packages with no 'Release' parameter value = value.rstrip('-') elif key == 'repoid': # Installed packages show a '@' at the beginning value = value.lstrip('@') cur[key] = value if key == 'repoid': # We're done with this package, create the pkginfo namedtuple pkginfo = salt.utils.pkg.rpm.pkginfo(**cur) # Clear the dict for the next package cur = {} # Yield the namedtuple if pkginfo is not None: yield pkginfo
[ "def", "_yum_pkginfo", "(", "output", ")", ":", "cur", "=", "{", "}", "keys", "=", "itertools", ".", "cycle", "(", "(", "'name'", ",", "'version'", ",", "'repoid'", ")", ")", "values", "=", "salt", ".", "utils", ".", "itertools", ".", "split", "(", ...
Parse yum/dnf output (which could contain irregular line breaks if package names are long) retrieving the name, version, etc., and return a list of pkginfo namedtuples.
[ "Parse", "yum", "/", "dnf", "output", "(", "which", "could", "contain", "irregular", "line", "breaks", "if", "package", "names", "are", "long", ")", "retrieving", "the", "name", "version", "etc", ".", "and", "return", "a", "list", "of", "pkginfo", "namedtu...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L173-L208
train
saltstack/salt
salt/modules/yumpkg.py
_check_versionlock
def _check_versionlock(): ''' Ensure that the appropriate versionlock plugin is present ''' if _yum() == 'dnf': if int(__grains__.get('osmajorrelease')) >= 26: if six.PY3: vl_plugin = 'python3-dnf-plugin-versionlock' else: vl_plugin = 'python2-dnf-plugin-versionlock' else: if six.PY3: vl_plugin = 'python3-dnf-plugins-extras-versionlock' else: vl_plugin = 'python-dnf-plugins-extras-versionlock' else: vl_plugin = 'yum-versionlock' \ if __grains__.get('osmajorrelease') == '5' \ else 'yum-plugin-versionlock' if vl_plugin not in list_pkgs(): raise SaltInvocationError( 'Cannot proceed, {0} is not installed.'.format(vl_plugin) )
python
def _check_versionlock(): ''' Ensure that the appropriate versionlock plugin is present ''' if _yum() == 'dnf': if int(__grains__.get('osmajorrelease')) >= 26: if six.PY3: vl_plugin = 'python3-dnf-plugin-versionlock' else: vl_plugin = 'python2-dnf-plugin-versionlock' else: if six.PY3: vl_plugin = 'python3-dnf-plugins-extras-versionlock' else: vl_plugin = 'python-dnf-plugins-extras-versionlock' else: vl_plugin = 'yum-versionlock' \ if __grains__.get('osmajorrelease') == '5' \ else 'yum-plugin-versionlock' if vl_plugin not in list_pkgs(): raise SaltInvocationError( 'Cannot proceed, {0} is not installed.'.format(vl_plugin) )
[ "def", "_check_versionlock", "(", ")", ":", "if", "_yum", "(", ")", "==", "'dnf'", ":", "if", "int", "(", "__grains__", ".", "get", "(", "'osmajorrelease'", ")", ")", ">=", "26", ":", "if", "six", ".", "PY3", ":", "vl_plugin", "=", "'python3-dnf-plugin...
Ensure that the appropriate versionlock plugin is present
[ "Ensure", "that", "the", "appropriate", "versionlock", "plugin", "is", "present" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L211-L234
train
saltstack/salt
salt/modules/yumpkg.py
_get_options
def _get_options(**kwargs): ''' Returns a list of options to be used in the yum/dnf command, based on the kwargs passed. ''' # Get repo options from the kwargs fromrepo = kwargs.pop('fromrepo', '') repo = kwargs.pop('repo', '') disablerepo = kwargs.pop('disablerepo', '') enablerepo = kwargs.pop('enablerepo', '') disableexcludes = kwargs.pop('disableexcludes', '') branch = kwargs.pop('branch', '') setopt = kwargs.pop('setopt', None) if setopt is None: setopt = [] else: setopt = salt.utils.args.split_input(setopt) get_extra_options = kwargs.pop('get_extra_options', False) # Support old 'repo' argument if repo and not fromrepo: fromrepo = repo ret = [] if fromrepo: log.info('Restricting to repo \'%s\'', fromrepo) ret.extend(['--disablerepo=*', '--enablerepo={0}'.format(fromrepo)]) else: if disablerepo: targets = [disablerepo] \ if not isinstance(disablerepo, list) \ else disablerepo log.info('Disabling repo(s): %s', ', '.join(targets)) ret.extend( ['--disablerepo={0}'.format(x) for x in targets] ) if enablerepo: targets = [enablerepo] \ if not isinstance(enablerepo, list) \ else enablerepo log.info('Enabling repo(s): %s', ', '.join(targets)) ret.extend(['--enablerepo={0}'.format(x) for x in targets]) if disableexcludes: log.info('Disabling excludes for \'%s\'', disableexcludes) ret.append('--disableexcludes={0}'.format(disableexcludes)) if branch: log.info('Adding branch \'%s\'', branch) ret.append('--branch={0}'.format(branch)) for item in setopt: ret.extend(['--setopt', six.text_type(item)]) if get_extra_options: # sorting here to make order uniform, makes unit testing more reliable for key in sorted(kwargs): if key.startswith('__'): continue value = kwargs[key] if isinstance(value, six.string_types): log.info('Found extra option --%s=%s', key, value) ret.append('--{0}={1}'.format(key, value)) elif value is True: log.info('Found extra option --%s', key) ret.append('--{0}'.format(key)) if ret: log.info('Adding extra options: %s', ret) return ret
python
def _get_options(**kwargs): ''' Returns a list of options to be used in the yum/dnf command, based on the kwargs passed. ''' # Get repo options from the kwargs fromrepo = kwargs.pop('fromrepo', '') repo = kwargs.pop('repo', '') disablerepo = kwargs.pop('disablerepo', '') enablerepo = kwargs.pop('enablerepo', '') disableexcludes = kwargs.pop('disableexcludes', '') branch = kwargs.pop('branch', '') setopt = kwargs.pop('setopt', None) if setopt is None: setopt = [] else: setopt = salt.utils.args.split_input(setopt) get_extra_options = kwargs.pop('get_extra_options', False) # Support old 'repo' argument if repo and not fromrepo: fromrepo = repo ret = [] if fromrepo: log.info('Restricting to repo \'%s\'', fromrepo) ret.extend(['--disablerepo=*', '--enablerepo={0}'.format(fromrepo)]) else: if disablerepo: targets = [disablerepo] \ if not isinstance(disablerepo, list) \ else disablerepo log.info('Disabling repo(s): %s', ', '.join(targets)) ret.extend( ['--disablerepo={0}'.format(x) for x in targets] ) if enablerepo: targets = [enablerepo] \ if not isinstance(enablerepo, list) \ else enablerepo log.info('Enabling repo(s): %s', ', '.join(targets)) ret.extend(['--enablerepo={0}'.format(x) for x in targets]) if disableexcludes: log.info('Disabling excludes for \'%s\'', disableexcludes) ret.append('--disableexcludes={0}'.format(disableexcludes)) if branch: log.info('Adding branch \'%s\'', branch) ret.append('--branch={0}'.format(branch)) for item in setopt: ret.extend(['--setopt', six.text_type(item)]) if get_extra_options: # sorting here to make order uniform, makes unit testing more reliable for key in sorted(kwargs): if key.startswith('__'): continue value = kwargs[key] if isinstance(value, six.string_types): log.info('Found extra option --%s=%s', key, value) ret.append('--{0}={1}'.format(key, value)) elif value is True: log.info('Found extra option --%s', key) ret.append('--{0}'.format(key)) if ret: log.info('Adding extra options: %s', ret) return ret
[ "def", "_get_options", "(", "*", "*", "kwargs", ")", ":", "# Get repo options from the kwargs", "fromrepo", "=", "kwargs", ".", "pop", "(", "'fromrepo'", ",", "''", ")", "repo", "=", "kwargs", ".", "pop", "(", "'repo'", ",", "''", ")", "disablerepo", "=", ...
Returns a list of options to be used in the yum/dnf command, based on the kwargs passed.
[ "Returns", "a", "list", "of", "options", "to", "be", "used", "in", "the", "yum", "/", "dnf", "command", "based", "on", "the", "kwargs", "passed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L237-L307
train
saltstack/salt
salt/modules/yumpkg.py
_get_yum_config
def _get_yum_config(): ''' Returns a dict representing the yum config options and values. We try to pull all of the yum config options into a standard dict object. This is currently only used to get the reposdir settings, but could be used for other things if needed. If the yum python library is available, use that, which will give us all of the options, including all of the defaults not specified in the yum config. Additionally, they will all be of the correct object type. If the yum library is not available, we try to read the yum.conf directly ourselves with a minimal set of "defaults". ''' # in case of any non-fatal failures, these defaults will be used conf = { 'reposdir': ['/etc/yum/repos.d', '/etc/yum.repos.d'], } if HAS_YUM: try: yb = yum.YumBase() yb.preconf.init_plugins = False for name, value in six.iteritems(yb.conf): conf[name] = value except (AttributeError, yum.Errors.ConfigError) as exc: raise CommandExecutionError( 'Could not query yum config: {0}'.format(exc) ) except yum.Errors.YumBaseError as yum_base_error: raise CommandExecutionError( 'Error accessing yum or rpmdb: {0}'.format(yum_base_error) ) else: # fall back to parsing the config ourselves # Look for the config the same order yum does fn = None paths = ('/etc/yum/yum.conf', '/etc/yum.conf', '/etc/dnf/dnf.conf', '/etc/tdnf/tdnf.conf') for path in paths: if os.path.exists(path): fn = path break if not fn: raise CommandExecutionError( 'No suitable yum config file found in: {0}'.format(paths) ) cp = configparser.ConfigParser() try: cp.read(fn) except (IOError, OSError) as exc: raise CommandExecutionError( 'Unable to read from {0}: {1}'.format(fn, exc) ) if cp.has_section('main'): for opt in cp.options('main'): if opt in ('reposdir', 'commands', 'excludes'): # these options are expected to be lists conf[opt] = [x.strip() for x in cp.get('main', opt).split(',')] else: conf[opt] = cp.get('main', opt) else: log.warning( 'Could not find [main] section in %s, using internal ' 'defaults', fn ) return conf
python
def _get_yum_config(): ''' Returns a dict representing the yum config options and values. We try to pull all of the yum config options into a standard dict object. This is currently only used to get the reposdir settings, but could be used for other things if needed. If the yum python library is available, use that, which will give us all of the options, including all of the defaults not specified in the yum config. Additionally, they will all be of the correct object type. If the yum library is not available, we try to read the yum.conf directly ourselves with a minimal set of "defaults". ''' # in case of any non-fatal failures, these defaults will be used conf = { 'reposdir': ['/etc/yum/repos.d', '/etc/yum.repos.d'], } if HAS_YUM: try: yb = yum.YumBase() yb.preconf.init_plugins = False for name, value in six.iteritems(yb.conf): conf[name] = value except (AttributeError, yum.Errors.ConfigError) as exc: raise CommandExecutionError( 'Could not query yum config: {0}'.format(exc) ) except yum.Errors.YumBaseError as yum_base_error: raise CommandExecutionError( 'Error accessing yum or rpmdb: {0}'.format(yum_base_error) ) else: # fall back to parsing the config ourselves # Look for the config the same order yum does fn = None paths = ('/etc/yum/yum.conf', '/etc/yum.conf', '/etc/dnf/dnf.conf', '/etc/tdnf/tdnf.conf') for path in paths: if os.path.exists(path): fn = path break if not fn: raise CommandExecutionError( 'No suitable yum config file found in: {0}'.format(paths) ) cp = configparser.ConfigParser() try: cp.read(fn) except (IOError, OSError) as exc: raise CommandExecutionError( 'Unable to read from {0}: {1}'.format(fn, exc) ) if cp.has_section('main'): for opt in cp.options('main'): if opt in ('reposdir', 'commands', 'excludes'): # these options are expected to be lists conf[opt] = [x.strip() for x in cp.get('main', opt).split(',')] else: conf[opt] = cp.get('main', opt) else: log.warning( 'Could not find [main] section in %s, using internal ' 'defaults', fn ) return conf
[ "def", "_get_yum_config", "(", ")", ":", "# in case of any non-fatal failures, these defaults will be used", "conf", "=", "{", "'reposdir'", ":", "[", "'/etc/yum/repos.d'", ",", "'/etc/yum.repos.d'", "]", ",", "}", "if", "HAS_YUM", ":", "try", ":", "yb", "=", "yum",...
Returns a dict representing the yum config options and values. We try to pull all of the yum config options into a standard dict object. This is currently only used to get the reposdir settings, but could be used for other things if needed. If the yum python library is available, use that, which will give us all of the options, including all of the defaults not specified in the yum config. Additionally, they will all be of the correct object type. If the yum library is not available, we try to read the yum.conf directly ourselves with a minimal set of "defaults".
[ "Returns", "a", "dict", "representing", "the", "yum", "config", "options", "and", "values", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L310-L382
train
saltstack/salt
salt/modules/yumpkg.py
_get_yum_config_value
def _get_yum_config_value(name): ''' Look for a specific config variable and return its value ''' conf = _get_yum_config() if name in conf.keys(): return conf.get(name) return None
python
def _get_yum_config_value(name): ''' Look for a specific config variable and return its value ''' conf = _get_yum_config() if name in conf.keys(): return conf.get(name) return None
[ "def", "_get_yum_config_value", "(", "name", ")", ":", "conf", "=", "_get_yum_config", "(", ")", "if", "name", "in", "conf", ".", "keys", "(", ")", ":", "return", "conf", ".", "get", "(", "name", ")", "return", "None" ]
Look for a specific config variable and return its value
[ "Look", "for", "a", "specific", "config", "variable", "and", "return", "its", "value" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L385-L392
train
saltstack/salt
salt/modules/yumpkg.py
_normalize_basedir
def _normalize_basedir(basedir=None): ''' Takes a basedir argument as a string or a list. If the string or list is empty, then look up the default from the 'reposdir' option in the yum config. Returns a list of directories. ''' # if we are passed a string (for backward compatibility), convert to a list if isinstance(basedir, six.string_types): basedir = [x.strip() for x in basedir.split(',')] if basedir is None: basedir = [] # nothing specified, so use the reposdir option as the default if not basedir: basedir = _get_yum_config_value('reposdir') if not isinstance(basedir, list) or not basedir: raise SaltInvocationError('Could not determine any repo directories') return basedir
python
def _normalize_basedir(basedir=None): ''' Takes a basedir argument as a string or a list. If the string or list is empty, then look up the default from the 'reposdir' option in the yum config. Returns a list of directories. ''' # if we are passed a string (for backward compatibility), convert to a list if isinstance(basedir, six.string_types): basedir = [x.strip() for x in basedir.split(',')] if basedir is None: basedir = [] # nothing specified, so use the reposdir option as the default if not basedir: basedir = _get_yum_config_value('reposdir') if not isinstance(basedir, list) or not basedir: raise SaltInvocationError('Could not determine any repo directories') return basedir
[ "def", "_normalize_basedir", "(", "basedir", "=", "None", ")", ":", "# if we are passed a string (for backward compatibility), convert to a list", "if", "isinstance", "(", "basedir", ",", "six", ".", "string_types", ")", ":", "basedir", "=", "[", "x", ".", "strip", ...
Takes a basedir argument as a string or a list. If the string or list is empty, then look up the default from the 'reposdir' option in the yum config. Returns a list of directories.
[ "Takes", "a", "basedir", "argument", "as", "a", "string", "or", "a", "list", ".", "If", "the", "string", "or", "list", "is", "empty", "then", "look", "up", "the", "default", "from", "the", "reposdir", "option", "in", "the", "yum", "config", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L395-L417
train
saltstack/salt
salt/modules/yumpkg.py
normalize_name
def normalize_name(name): ''' Strips the architecture from the specified package name, if necessary. Circumstances where this would be done include: * If the arch is 32 bit and the package name ends in a 32-bit arch. * If the arch matches the OS arch, or is ``noarch``. CLI Example: .. code-block:: bash salt '*' pkg.normalize_name zsh.x86_64 ''' try: arch = name.rsplit('.', 1)[-1] if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',): return name except ValueError: return name if arch in (__grains__['osarch'], 'noarch') \ or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']): return name[:-(len(arch) + 1)] return name
python
def normalize_name(name): ''' Strips the architecture from the specified package name, if necessary. Circumstances where this would be done include: * If the arch is 32 bit and the package name ends in a 32-bit arch. * If the arch matches the OS arch, or is ``noarch``. CLI Example: .. code-block:: bash salt '*' pkg.normalize_name zsh.x86_64 ''' try: arch = name.rsplit('.', 1)[-1] if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',): return name except ValueError: return name if arch in (__grains__['osarch'], 'noarch') \ or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']): return name[:-(len(arch) + 1)] return name
[ "def", "normalize_name", "(", "name", ")", ":", "try", ":", "arch", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "-", "1", "]", "if", "arch", "not", "in", "salt", ".", "utils", ".", "pkg", ".", "rpm", ".", "ARCHES", "+", "(", "...
Strips the architecture from the specified package name, if necessary. Circumstances where this would be done include: * If the arch is 32 bit and the package name ends in a 32-bit arch. * If the arch matches the OS arch, or is ``noarch``. CLI Example: .. code-block:: bash salt '*' pkg.normalize_name zsh.x86_64
[ "Strips", "the", "architecture", "from", "the", "specified", "package", "name", "if", "necessary", ".", "Circumstances", "where", "this", "would", "be", "done", "include", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L420-L443
train
saltstack/salt
salt/modules/yumpkg.py
version_cmp
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): ''' .. versionadded:: 2015.5.4 Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. ignore_epoch : False Set to ``True`` to ignore the epoch when comparing versions .. versionadded:: 2015.8.10,2016.3.2 CLI Example: .. code-block:: bash salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002' ''' return __salt__['lowpkg.version_cmp'](pkg1, pkg2, ignore_epoch=ignore_epoch)
python
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): ''' .. versionadded:: 2015.5.4 Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. ignore_epoch : False Set to ``True`` to ignore the epoch when comparing versions .. versionadded:: 2015.8.10,2016.3.2 CLI Example: .. code-block:: bash salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002' ''' return __salt__['lowpkg.version_cmp'](pkg1, pkg2, ignore_epoch=ignore_epoch)
[ "def", "version_cmp", "(", "pkg1", ",", "pkg2", ",", "ignore_epoch", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "__salt__", "[", "'lowpkg.version_cmp'", "]", "(", "pkg1", ",", "pkg2", ",", "ignore_epoch", "=", "ignore_epoch", ")" ]
.. versionadded:: 2015.5.4 Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. ignore_epoch : False Set to ``True`` to ignore the epoch when comparing versions .. versionadded:: 2015.8.10,2016.3.2 CLI Example: .. code-block:: bash salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
[ "..", "versionadded", "::", "2015", ".", "5", ".", "4" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L599-L619
train
saltstack/salt
salt/modules/yumpkg.py
list_pkgs
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict. By default, the dict contains versions as a comma separated string:: {'<package_name>': '<version>[,<version>...]'} versions_as_list: If set to true, the versions are provided as a list {'<package_name>': ['<version>', '<version>']} attr: If a list of package attributes is specified, returned value will contain them in addition to version, eg.:: {'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]} Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``, ``install_date``, ``install_date_time_t``. If ``all`` is specified, all valid attributes will be returned. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs attr=version,arch salt '*' pkg.list_pkgs attr='["version", "arch"]' ''' 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 {} attr = kwargs.get('attr') if attr is not None: attr = salt.utils.args.split_input(attr) contextkey = 'pkg.list_pkgs' if contextkey not in __context__: ret = {} cmd = ['rpm', '-qa', '--queryformat', salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'] output = __salt__['cmd.run'](cmd, python_shell=False, output_loglevel='trace') for line in output.splitlines(): pkginfo = salt.utils.pkg.rpm.parse_pkginfo( line, osarch=__grains__['osarch'] ) if pkginfo is not None: # see rpm version string rules available at https://goo.gl/UGKPNd pkgver = pkginfo.version epoch = '' release = '' if ':' in pkgver: epoch, pkgver = pkgver.split(":", 1) if '-' in pkgver: pkgver, release = pkgver.split("-", 1) all_attr = { 'epoch': epoch, 'version': pkgver, 'release': release, 'arch': pkginfo.arch, 'install_date': pkginfo.install_date, 'install_date_time_t': pkginfo.install_date_time_t } __salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr) for pkgname in ret: ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version']) __context__[contextkey] = ret return __salt__['pkg_resource.format_pkg_list']( __context__[contextkey], versions_as_list, attr)
python
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict. By default, the dict contains versions as a comma separated string:: {'<package_name>': '<version>[,<version>...]'} versions_as_list: If set to true, the versions are provided as a list {'<package_name>': ['<version>', '<version>']} attr: If a list of package attributes is specified, returned value will contain them in addition to version, eg.:: {'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]} Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``, ``install_date``, ``install_date_time_t``. If ``all`` is specified, all valid attributes will be returned. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs attr=version,arch salt '*' pkg.list_pkgs attr='["version", "arch"]' ''' 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 {} attr = kwargs.get('attr') if attr is not None: attr = salt.utils.args.split_input(attr) contextkey = 'pkg.list_pkgs' if contextkey not in __context__: ret = {} cmd = ['rpm', '-qa', '--queryformat', salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'] output = __salt__['cmd.run'](cmd, python_shell=False, output_loglevel='trace') for line in output.splitlines(): pkginfo = salt.utils.pkg.rpm.parse_pkginfo( line, osarch=__grains__['osarch'] ) if pkginfo is not None: # see rpm version string rules available at https://goo.gl/UGKPNd pkgver = pkginfo.version epoch = '' release = '' if ':' in pkgver: epoch, pkgver = pkgver.split(":", 1) if '-' in pkgver: pkgver, release = pkgver.split("-", 1) all_attr = { 'epoch': epoch, 'version': pkgver, 'release': release, 'arch': pkginfo.arch, 'install_date': pkginfo.install_date, 'install_date_time_t': pkginfo.install_date_time_t } __salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr) for pkgname in ret: ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version']) __context__[contextkey] = ret return __salt__['pkg_resource.format_pkg_list']( __context__[contextkey], versions_as_list, attr)
[ "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. By default, the dict contains versions as a comma separated string:: {'<package_name>': '<version>[,<version>...]'} versions_as_list: If set to true, the versions are provided as a list {'<package_name>': ['<version>', '<version>']} attr: If a list of package attributes is specified, returned value will contain them in addition to version, eg.:: {'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]} Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``, ``install_date``, ``install_date_time_t``. If ``all`` is specified, all valid attributes will be returned. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs attr=version,arch salt '*' pkg.list_pkgs attr='["version", "arch"]'
[ "List", "the", "packages", "currently", "installed", "as", "a", "dict", ".", "By", "default", "the", "dict", "contains", "versions", "as", "a", "comma", "separated", "string", "::" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L622-L706
train
saltstack/salt
salt/modules/yumpkg.py
list_repo_pkgs
def list_repo_pkgs(*args, **kwargs): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2014.7.0 All available versions of each package are now returned. This required a slight modification to the structure of the return dict. The return data shown below reflects the updated return dict structure. Note that packages which are version-locked using :py:mod:`pkg.hold <salt.modules.yumpkg.hold>` will only show the currently-installed version, as locking a package will make other versions appear unavailable to yum/dnf. .. versionchanged:: 2017.7.0 By default, the versions for each package are no longer organized by repository. To get results organized by repository, use ``byrepo=True``. Returns all available packages. Optionally, package names (and name globs) can be passed and the results will be filtered to packages matching those names. This is recommended as it speeds up the function considerably. .. warning:: Running this function on RHEL/CentOS 6 and earlier will be more resource-intensive, as the version of yum that ships with older RHEL/CentOS has no yum subcommand for listing packages from a repository. Thus, a ``yum list installed`` and ``yum list available`` are run, which generates a lot of output, which must then be analyzed to determine which package information to include in the return data. This function can be helpful in discovering the version or repo to specify in a :mod:`pkg.installed <salt.states.pkg.installed>` state. The return data will be a dictionary mapping package names to a list of version numbers, ordered from newest to oldest. If ``byrepo`` is set to ``True``, then the return dictionary will contain repository names at the top level, and each repository will map packages to lists of version numbers. For example: .. code-block:: python # With byrepo=False (default) { 'bash': ['4.1.2-15.el6_5.2', '4.1.2-15.el6_5.1', '4.1.2-15.el6_4'], 'kernel': ['2.6.32-431.29.2.el6', '2.6.32-431.23.3.el6', '2.6.32-431.20.5.el6', '2.6.32-431.20.3.el6', '2.6.32-431.17.1.el6', '2.6.32-431.11.2.el6', '2.6.32-431.5.1.el6', '2.6.32-431.3.1.el6', '2.6.32-431.1.2.0.1.el6', '2.6.32-431.el6'] } # With byrepo=True { 'base': { 'bash': ['4.1.2-15.el6_4'], 'kernel': ['2.6.32-431.el6'] }, 'updates': { 'bash': ['4.1.2-15.el6_5.2', '4.1.2-15.el6_5.1'], 'kernel': ['2.6.32-431.29.2.el6', '2.6.32-431.23.3.el6', '2.6.32-431.20.5.el6', '2.6.32-431.20.3.el6', '2.6.32-431.17.1.el6', '2.6.32-431.11.2.el6', '2.6.32-431.5.1.el6', '2.6.32-431.3.1.el6', '2.6.32-431.1.2.0.1.el6'] } } fromrepo : None Only include results from the specified repo(s). Multiple repos can be specified, comma-separated. enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) .. versionadded:: 2017.7.0 disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) .. versionadded:: 2017.7.0 byrepo : False When ``True``, the return data for each package will be organized by repository. .. versionadded:: 2017.7.0 cacheonly : False When ``True``, the repo information will be retrieved from the cached repo metadata. This is equivalent to passing the ``-C`` option to yum/dnf. .. versionadded:: 2017.7.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 CLI Examples: .. code-block:: bash salt '*' pkg.list_repo_pkgs salt '*' pkg.list_repo_pkgs foo bar baz salt '*' pkg.list_repo_pkgs 'samba4*' fromrepo=base,updates salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True ''' byrepo = kwargs.pop('byrepo', False) cacheonly = kwargs.pop('cacheonly', False) fromrepo = kwargs.pop('fromrepo', '') or '' disablerepo = kwargs.pop('disablerepo', '') or '' enablerepo = kwargs.pop('enablerepo', '') or '' repo_arg = _get_options(fromrepo=fromrepo, **kwargs) if fromrepo and not isinstance(fromrepo, list): try: fromrepo = [x.strip() for x in fromrepo.split(',')] except AttributeError: fromrepo = [x.strip() for x in six.text_type(fromrepo).split(',')] if disablerepo and not isinstance(disablerepo, list): try: disablerepo = [x.strip() for x in disablerepo.split(',') if x != '*'] except AttributeError: disablerepo = [x.strip() for x in six.text_type(disablerepo).split(',') if x != '*'] if enablerepo and not isinstance(enablerepo, list): try: enablerepo = [x.strip() for x in enablerepo.split(',') if x != '*'] except AttributeError: enablerepo = [x.strip() for x in six.text_type(enablerepo).split(',') if x != '*'] if fromrepo: repos = fromrepo else: repos = [ repo_name for repo_name, repo_info in six.iteritems(list_repos()) if repo_name in enablerepo or (repo_name not in disablerepo and six.text_type(repo_info.get('enabled', '1')) == '1') ] ret = {} def _check_args(args, name): ''' Do glob matching on args and return True if a match was found. Otherwise, return False ''' for arg in args: if fnmatch.fnmatch(name, arg): return True return False def _parse_output(output, strict=False): for pkg in _yum_pkginfo(output): if strict and (pkg.repoid not in repos or not _check_args(args, pkg.name)): continue repo_dict = ret.setdefault(pkg.repoid, {}) version_list = repo_dict.setdefault(pkg.name, set()) version_list.add(pkg.version) yum_version = None if _yum() != 'yum' else _LooseVersion( __salt__['cmd.run']( ['yum', '--version'], python_shell=False ).splitlines()[0].strip() ) # Really old version of yum; does not even have --showduplicates option if yum_version and yum_version < _LooseVersion('3.2.13'): cmd_prefix = ['--quiet'] if cacheonly: cmd_prefix.append('-C') cmd_prefix.append('list') for pkg_src in ('installed', 'available'): # Check installed packages first out = _call_yum(cmd_prefix + [pkg_src], ignore_retcode=True) if out['retcode'] == 0: _parse_output(out['stdout'], strict=True) # The --showduplicates option is added in 3.2.13, but the # repository-packages subcommand is only in 3.4.3 and newer elif yum_version and yum_version < _LooseVersion('3.4.3'): cmd_prefix = ['--quiet', '--showduplicates'] if cacheonly: cmd_prefix.append('-C') cmd_prefix.append('list') for pkg_src in ('installed', 'available'): # Check installed packages first out = _call_yum(cmd_prefix + [pkg_src], ignore_retcode=True) if out['retcode'] == 0: _parse_output(out['stdout'], strict=True) else: for repo in repos: cmd = ['--quiet', '--showduplicates', 'repository-packages', repo, 'list'] if cacheonly: cmd.append('-C') # Can't concatenate because args is a tuple, using list.extend() cmd.extend(args) out = _call_yum(cmd, ignore_retcode=True) if out['retcode'] != 0 and 'Error:' in out['stdout']: continue _parse_output(out['stdout']) if byrepo: for reponame in ret: # Sort versions newest to oldest for pkgname in ret[reponame]: sorted_versions = sorted( [_LooseVersion(x) for x in ret[reponame][pkgname]], reverse=True ) ret[reponame][pkgname] = [x.vstring for x in sorted_versions] return ret else: byrepo_ret = {} for reponame in ret: for pkgname in ret[reponame]: byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname]) for pkgname in byrepo_ret: sorted_versions = sorted( [_LooseVersion(x) for x in byrepo_ret[pkgname]], reverse=True ) byrepo_ret[pkgname] = [x.vstring for x in sorted_versions] return byrepo_ret
python
def list_repo_pkgs(*args, **kwargs): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2014.7.0 All available versions of each package are now returned. This required a slight modification to the structure of the return dict. The return data shown below reflects the updated return dict structure. Note that packages which are version-locked using :py:mod:`pkg.hold <salt.modules.yumpkg.hold>` will only show the currently-installed version, as locking a package will make other versions appear unavailable to yum/dnf. .. versionchanged:: 2017.7.0 By default, the versions for each package are no longer organized by repository. To get results organized by repository, use ``byrepo=True``. Returns all available packages. Optionally, package names (and name globs) can be passed and the results will be filtered to packages matching those names. This is recommended as it speeds up the function considerably. .. warning:: Running this function on RHEL/CentOS 6 and earlier will be more resource-intensive, as the version of yum that ships with older RHEL/CentOS has no yum subcommand for listing packages from a repository. Thus, a ``yum list installed`` and ``yum list available`` are run, which generates a lot of output, which must then be analyzed to determine which package information to include in the return data. This function can be helpful in discovering the version or repo to specify in a :mod:`pkg.installed <salt.states.pkg.installed>` state. The return data will be a dictionary mapping package names to a list of version numbers, ordered from newest to oldest. If ``byrepo`` is set to ``True``, then the return dictionary will contain repository names at the top level, and each repository will map packages to lists of version numbers. For example: .. code-block:: python # With byrepo=False (default) { 'bash': ['4.1.2-15.el6_5.2', '4.1.2-15.el6_5.1', '4.1.2-15.el6_4'], 'kernel': ['2.6.32-431.29.2.el6', '2.6.32-431.23.3.el6', '2.6.32-431.20.5.el6', '2.6.32-431.20.3.el6', '2.6.32-431.17.1.el6', '2.6.32-431.11.2.el6', '2.6.32-431.5.1.el6', '2.6.32-431.3.1.el6', '2.6.32-431.1.2.0.1.el6', '2.6.32-431.el6'] } # With byrepo=True { 'base': { 'bash': ['4.1.2-15.el6_4'], 'kernel': ['2.6.32-431.el6'] }, 'updates': { 'bash': ['4.1.2-15.el6_5.2', '4.1.2-15.el6_5.1'], 'kernel': ['2.6.32-431.29.2.el6', '2.6.32-431.23.3.el6', '2.6.32-431.20.5.el6', '2.6.32-431.20.3.el6', '2.6.32-431.17.1.el6', '2.6.32-431.11.2.el6', '2.6.32-431.5.1.el6', '2.6.32-431.3.1.el6', '2.6.32-431.1.2.0.1.el6'] } } fromrepo : None Only include results from the specified repo(s). Multiple repos can be specified, comma-separated. enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) .. versionadded:: 2017.7.0 disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) .. versionadded:: 2017.7.0 byrepo : False When ``True``, the return data for each package will be organized by repository. .. versionadded:: 2017.7.0 cacheonly : False When ``True``, the repo information will be retrieved from the cached repo metadata. This is equivalent to passing the ``-C`` option to yum/dnf. .. versionadded:: 2017.7.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 CLI Examples: .. code-block:: bash salt '*' pkg.list_repo_pkgs salt '*' pkg.list_repo_pkgs foo bar baz salt '*' pkg.list_repo_pkgs 'samba4*' fromrepo=base,updates salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True ''' byrepo = kwargs.pop('byrepo', False) cacheonly = kwargs.pop('cacheonly', False) fromrepo = kwargs.pop('fromrepo', '') or '' disablerepo = kwargs.pop('disablerepo', '') or '' enablerepo = kwargs.pop('enablerepo', '') or '' repo_arg = _get_options(fromrepo=fromrepo, **kwargs) if fromrepo and not isinstance(fromrepo, list): try: fromrepo = [x.strip() for x in fromrepo.split(',')] except AttributeError: fromrepo = [x.strip() for x in six.text_type(fromrepo).split(',')] if disablerepo and not isinstance(disablerepo, list): try: disablerepo = [x.strip() for x in disablerepo.split(',') if x != '*'] except AttributeError: disablerepo = [x.strip() for x in six.text_type(disablerepo).split(',') if x != '*'] if enablerepo and not isinstance(enablerepo, list): try: enablerepo = [x.strip() for x in enablerepo.split(',') if x != '*'] except AttributeError: enablerepo = [x.strip() for x in six.text_type(enablerepo).split(',') if x != '*'] if fromrepo: repos = fromrepo else: repos = [ repo_name for repo_name, repo_info in six.iteritems(list_repos()) if repo_name in enablerepo or (repo_name not in disablerepo and six.text_type(repo_info.get('enabled', '1')) == '1') ] ret = {} def _check_args(args, name): ''' Do glob matching on args and return True if a match was found. Otherwise, return False ''' for arg in args: if fnmatch.fnmatch(name, arg): return True return False def _parse_output(output, strict=False): for pkg in _yum_pkginfo(output): if strict and (pkg.repoid not in repos or not _check_args(args, pkg.name)): continue repo_dict = ret.setdefault(pkg.repoid, {}) version_list = repo_dict.setdefault(pkg.name, set()) version_list.add(pkg.version) yum_version = None if _yum() != 'yum' else _LooseVersion( __salt__['cmd.run']( ['yum', '--version'], python_shell=False ).splitlines()[0].strip() ) # Really old version of yum; does not even have --showduplicates option if yum_version and yum_version < _LooseVersion('3.2.13'): cmd_prefix = ['--quiet'] if cacheonly: cmd_prefix.append('-C') cmd_prefix.append('list') for pkg_src in ('installed', 'available'): # Check installed packages first out = _call_yum(cmd_prefix + [pkg_src], ignore_retcode=True) if out['retcode'] == 0: _parse_output(out['stdout'], strict=True) # The --showduplicates option is added in 3.2.13, but the # repository-packages subcommand is only in 3.4.3 and newer elif yum_version and yum_version < _LooseVersion('3.4.3'): cmd_prefix = ['--quiet', '--showduplicates'] if cacheonly: cmd_prefix.append('-C') cmd_prefix.append('list') for pkg_src in ('installed', 'available'): # Check installed packages first out = _call_yum(cmd_prefix + [pkg_src], ignore_retcode=True) if out['retcode'] == 0: _parse_output(out['stdout'], strict=True) else: for repo in repos: cmd = ['--quiet', '--showduplicates', 'repository-packages', repo, 'list'] if cacheonly: cmd.append('-C') # Can't concatenate because args is a tuple, using list.extend() cmd.extend(args) out = _call_yum(cmd, ignore_retcode=True) if out['retcode'] != 0 and 'Error:' in out['stdout']: continue _parse_output(out['stdout']) if byrepo: for reponame in ret: # Sort versions newest to oldest for pkgname in ret[reponame]: sorted_versions = sorted( [_LooseVersion(x) for x in ret[reponame][pkgname]], reverse=True ) ret[reponame][pkgname] = [x.vstring for x in sorted_versions] return ret else: byrepo_ret = {} for reponame in ret: for pkgname in ret[reponame]: byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname]) for pkgname in byrepo_ret: sorted_versions = sorted( [_LooseVersion(x) for x in byrepo_ret[pkgname]], reverse=True ) byrepo_ret[pkgname] = [x.vstring for x in sorted_versions] return byrepo_ret
[ "def", "list_repo_pkgs", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "byrepo", "=", "kwargs", ".", "pop", "(", "'byrepo'", ",", "False", ")", "cacheonly", "=", "kwargs", ".", "pop", "(", "'cacheonly'", ",", "False", ")", "fromrepo", "=", "kw...
.. versionadded:: 2014.1.0 .. versionchanged:: 2014.7.0 All available versions of each package are now returned. This required a slight modification to the structure of the return dict. The return data shown below reflects the updated return dict structure. Note that packages which are version-locked using :py:mod:`pkg.hold <salt.modules.yumpkg.hold>` will only show the currently-installed version, as locking a package will make other versions appear unavailable to yum/dnf. .. versionchanged:: 2017.7.0 By default, the versions for each package are no longer organized by repository. To get results organized by repository, use ``byrepo=True``. Returns all available packages. Optionally, package names (and name globs) can be passed and the results will be filtered to packages matching those names. This is recommended as it speeds up the function considerably. .. warning:: Running this function on RHEL/CentOS 6 and earlier will be more resource-intensive, as the version of yum that ships with older RHEL/CentOS has no yum subcommand for listing packages from a repository. Thus, a ``yum list installed`` and ``yum list available`` are run, which generates a lot of output, which must then be analyzed to determine which package information to include in the return data. This function can be helpful in discovering the version or repo to specify in a :mod:`pkg.installed <salt.states.pkg.installed>` state. The return data will be a dictionary mapping package names to a list of version numbers, ordered from newest to oldest. If ``byrepo`` is set to ``True``, then the return dictionary will contain repository names at the top level, and each repository will map packages to lists of version numbers. For example: .. code-block:: python # With byrepo=False (default) { 'bash': ['4.1.2-15.el6_5.2', '4.1.2-15.el6_5.1', '4.1.2-15.el6_4'], 'kernel': ['2.6.32-431.29.2.el6', '2.6.32-431.23.3.el6', '2.6.32-431.20.5.el6', '2.6.32-431.20.3.el6', '2.6.32-431.17.1.el6', '2.6.32-431.11.2.el6', '2.6.32-431.5.1.el6', '2.6.32-431.3.1.el6', '2.6.32-431.1.2.0.1.el6', '2.6.32-431.el6'] } # With byrepo=True { 'base': { 'bash': ['4.1.2-15.el6_4'], 'kernel': ['2.6.32-431.el6'] }, 'updates': { 'bash': ['4.1.2-15.el6_5.2', '4.1.2-15.el6_5.1'], 'kernel': ['2.6.32-431.29.2.el6', '2.6.32-431.23.3.el6', '2.6.32-431.20.5.el6', '2.6.32-431.20.3.el6', '2.6.32-431.17.1.el6', '2.6.32-431.11.2.el6', '2.6.32-431.5.1.el6', '2.6.32-431.3.1.el6', '2.6.32-431.1.2.0.1.el6'] } } fromrepo : None Only include results from the specified repo(s). Multiple repos can be specified, comma-separated. enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) .. versionadded:: 2017.7.0 disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) .. versionadded:: 2017.7.0 byrepo : False When ``True``, the return data for each package will be organized by repository. .. versionadded:: 2017.7.0 cacheonly : False When ``True``, the repo information will be retrieved from the cached repo metadata. This is equivalent to passing the ``-C`` option to yum/dnf. .. versionadded:: 2017.7.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 CLI Examples: .. code-block:: bash salt '*' pkg.list_repo_pkgs salt '*' pkg.list_repo_pkgs foo bar baz salt '*' pkg.list_repo_pkgs 'samba4*' fromrepo=base,updates salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0", "..", "versionchanged", "::", "2014", ".", "7", ".", "0", "All", "available", "versions", "of", "each", "package", "are", "now", "returned", ".", "This", "required", "a", "slight", "modification", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L709-L952
train
saltstack/salt
salt/modules/yumpkg.py
list_upgrades
def list_upgrades(refresh=True, **kwargs): ''' Check whether or not an upgrade is available for all packages The ``fromrepo``, ``enablerepo``, and ``disablerepo`` arguments are supported, as used in pkg states, and the ``disableexcludes`` option is also supported. .. versionadded:: 2014.7.0 Support for the ``disableexcludes`` option CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' options = _get_options(**kwargs) if salt.utils.data.is_true(refresh): refresh_db(check_update=False, **kwargs) cmd = ['--quiet'] cmd.extend(options) cmd.extend(['list', 'upgrades' if _yum() == 'dnf' else 'updates']) out = _call_yum(cmd, ignore_retcode=True) if out['retcode'] != 0 and 'Error:' in out: return {} return dict([(x.name, x.version) for x in _yum_pkginfo(out['stdout'])])
python
def list_upgrades(refresh=True, **kwargs): ''' Check whether or not an upgrade is available for all packages The ``fromrepo``, ``enablerepo``, and ``disablerepo`` arguments are supported, as used in pkg states, and the ``disableexcludes`` option is also supported. .. versionadded:: 2014.7.0 Support for the ``disableexcludes`` option CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' options = _get_options(**kwargs) if salt.utils.data.is_true(refresh): refresh_db(check_update=False, **kwargs) cmd = ['--quiet'] cmd.extend(options) cmd.extend(['list', 'upgrades' if _yum() == 'dnf' else 'updates']) out = _call_yum(cmd, ignore_retcode=True) if out['retcode'] != 0 and 'Error:' in out: return {} return dict([(x.name, x.version) for x in _yum_pkginfo(out['stdout'])])
[ "def", "list_upgrades", "(", "refresh", "=", "True", ",", "*", "*", "kwargs", ")", ":", "options", "=", "_get_options", "(", "*", "*", "kwargs", ")", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "refresh", ")", ":", "refresh_db", "("...
Check whether or not an upgrade is available for all packages The ``fromrepo``, ``enablerepo``, and ``disablerepo`` arguments are supported, as used in pkg states, and the ``disableexcludes`` option is also supported. .. versionadded:: 2014.7.0 Support for the ``disableexcludes`` option CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades
[ "Check", "whether", "or", "not", "an", "upgrade", "is", "available", "for", "all", "packages" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L955-L984
train
saltstack/salt
salt/modules/yumpkg.py
list_downloaded
def list_downloaded(**kwargs): ''' .. versionadded:: 2017.7.0 List prefetched packages downloaded by Yum in the local disk. CLI example: .. code-block:: bash salt '*' pkg.list_downloaded ''' CACHE_DIR = os.path.join('/var/cache/', _yum()) ret = {} for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR): for filename in fnmatch.filter(filenames, '*.rpm'): package_path = os.path.join(root, filename) pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path) pkg_timestamp = int(os.path.getctime(package_path)) ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = { 'path': package_path, 'size': os.path.getsize(package_path), 'creation_date_time_t': pkg_timestamp, 'creation_date_time': datetime.datetime.fromtimestamp(pkg_timestamp).isoformat(), } return ret
python
def list_downloaded(**kwargs): ''' .. versionadded:: 2017.7.0 List prefetched packages downloaded by Yum in the local disk. CLI example: .. code-block:: bash salt '*' pkg.list_downloaded ''' CACHE_DIR = os.path.join('/var/cache/', _yum()) ret = {} for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR): for filename in fnmatch.filter(filenames, '*.rpm'): package_path = os.path.join(root, filename) pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path) pkg_timestamp = int(os.path.getctime(package_path)) ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = { 'path': package_path, 'size': os.path.getsize(package_path), 'creation_date_time_t': pkg_timestamp, 'creation_date_time': datetime.datetime.fromtimestamp(pkg_timestamp).isoformat(), } return ret
[ "def", "list_downloaded", "(", "*", "*", "kwargs", ")", ":", "CACHE_DIR", "=", "os", ".", "path", ".", "join", "(", "'/var/cache/'", ",", "_yum", "(", ")", ")", "ret", "=", "{", "}", "for", "root", ",", "dirnames", ",", "filenames", "in", "salt", "...
.. versionadded:: 2017.7.0 List prefetched packages downloaded by Yum in the local disk. CLI example: .. code-block:: bash salt '*' pkg.list_downloaded
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L991-L1017
train
saltstack/salt
salt/modules/yumpkg.py
info_installed
def info_installed(*names, **kwargs): ''' .. versionadded:: 2015.8.1 Return the information of the named package(s), installed on the system. :param all_versions: Include information for all versions of the packages installed on the minion. CLI example: .. code-block:: bash salt '*' pkg.info_installed <package1> salt '*' pkg.info_installed <package1> <package2> <package3> ... salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True ''' all_versions = kwargs.get('all_versions', False) ret = dict() for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items(): pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo] for _nfo in pkg_nfo: t_nfo = dict() # Translate dpkg-specific keys to a common structure for key, value in _nfo.items(): if key == 'source_rpm': t_nfo['source'] = value else: t_nfo[key] = value if not all_versions: ret[pkg_name] = t_nfo else: ret.setdefault(pkg_name, []).append(t_nfo) return ret
python
def info_installed(*names, **kwargs): ''' .. versionadded:: 2015.8.1 Return the information of the named package(s), installed on the system. :param all_versions: Include information for all versions of the packages installed on the minion. CLI example: .. code-block:: bash salt '*' pkg.info_installed <package1> salt '*' pkg.info_installed <package1> <package2> <package3> ... salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True ''' all_versions = kwargs.get('all_versions', False) ret = dict() for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items(): pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo] for _nfo in pkg_nfo: t_nfo = dict() # Translate dpkg-specific keys to a common structure for key, value in _nfo.items(): if key == 'source_rpm': t_nfo['source'] = value else: t_nfo[key] = value if not all_versions: ret[pkg_name] = t_nfo else: ret.setdefault(pkg_name, []).append(t_nfo) return ret
[ "def", "info_installed", "(", "*", "names", ",", "*", "*", "kwargs", ")", ":", "all_versions", "=", "kwargs", ".", "get", "(", "'all_versions'", ",", "False", ")", "ret", "=", "dict", "(", ")", "for", "pkg_name", ",", "pkgs_nfo", "in", "__salt__", "[",...
.. versionadded:: 2015.8.1 Return the information of the named package(s), installed on the system. :param all_versions: Include information for all versions of the packages installed on the minion. CLI example: .. code-block:: bash salt '*' pkg.info_installed <package1> salt '*' pkg.info_installed <package1> <package2> <package3> ... salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
[ "..", "versionadded", "::", "2015", ".", "8", ".", "1" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L1020-L1053
train
saltstack/salt
salt/modules/yumpkg.py
refresh_db
def refresh_db(**kwargs): ''' Check the yum repos for updated packages Returns: - ``True``: Updates are available - ``False``: An error occurred - ``None``: No updates are available repo Refresh just the specified repo disablerepo Do not refresh the specified repo enablerepo Refresh a disabled repo using this option branch Add the specified branch when refreshing disableexcludes Disable the excludes defined in your config files. Takes one of three options: - ``all`` - disable all excludes - ``main`` - disable excludes defined in [main] in yum.conf - ``repoid`` - disable excludes defined for that repo setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' # Remove rtag file to keep multiple refreshes from happening in pkg states salt.utils.pkg.clear_rtag(__opts__) retcodes = { 100: True, 0: None, 1: False, } ret = True check_update_ = kwargs.pop('check_update', True) options = _get_options(**kwargs) clean_cmd = ['--quiet', '--assumeyes', 'clean', 'expire-cache'] clean_cmd.extend(options) _call_yum(clean_cmd, ignore_retcode=True) if check_update_: update_cmd = ['--quiet', '--assumeyes', 'check-update'] if (__grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == 7): # This feature is disabled because it is not used by Salt and adds a # lot of extra time to the command with large repos like EPEL update_cmd.append('--setopt=autocheck_running_kernel=false') update_cmd.extend(options) ret = retcodes.get(_call_yum(update_cmd, ignore_retcode=True)['retcode'], False) return ret
python
def refresh_db(**kwargs): ''' Check the yum repos for updated packages Returns: - ``True``: Updates are available - ``False``: An error occurred - ``None``: No updates are available repo Refresh just the specified repo disablerepo Do not refresh the specified repo enablerepo Refresh a disabled repo using this option branch Add the specified branch when refreshing disableexcludes Disable the excludes defined in your config files. Takes one of three options: - ``all`` - disable all excludes - ``main`` - disable excludes defined in [main] in yum.conf - ``repoid`` - disable excludes defined for that repo setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' # Remove rtag file to keep multiple refreshes from happening in pkg states salt.utils.pkg.clear_rtag(__opts__) retcodes = { 100: True, 0: None, 1: False, } ret = True check_update_ = kwargs.pop('check_update', True) options = _get_options(**kwargs) clean_cmd = ['--quiet', '--assumeyes', 'clean', 'expire-cache'] clean_cmd.extend(options) _call_yum(clean_cmd, ignore_retcode=True) if check_update_: update_cmd = ['--quiet', '--assumeyes', 'check-update'] if (__grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == 7): # This feature is disabled because it is not used by Salt and adds a # lot of extra time to the command with large repos like EPEL update_cmd.append('--setopt=autocheck_running_kernel=false') update_cmd.extend(options) ret = retcodes.get(_call_yum(update_cmd, ignore_retcode=True)['retcode'], False) return ret
[ "def", "refresh_db", "(", "*", "*", "kwargs", ")", ":", "# Remove rtag file to keep multiple refreshes from happening in pkg states", "salt", ".", "utils", ".", "pkg", ".", "clear_rtag", "(", "__opts__", ")", "retcodes", "=", "{", "100", ":", "True", ",", "0", "...
Check the yum repos for updated packages Returns: - ``True``: Updates are available - ``False``: An error occurred - ``None``: No updates are available repo Refresh just the specified repo disablerepo Do not refresh the specified repo enablerepo Refresh a disabled repo using this option branch Add the specified branch when refreshing disableexcludes Disable the excludes defined in your config files. Takes one of three options: - ``all`` - disable all excludes - ``main`` - disable excludes defined in [main] in yum.conf - ``repoid`` - disable excludes defined for that repo setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' pkg.refresh_db
[ "Check", "the", "yum", "repos", "for", "updated", "packages" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L1056-L1124
train
saltstack/salt
salt/modules/yumpkg.py
install
def install(name=None, refresh=False, skip_verify=False, pkgs=None, sources=None, downloadonly=False, reinstall=False, normalize=True, update_holds=False, saltenv='base', ignore_epoch=False, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Install the passed package(s), add refresh=True to clean the yum database before package is installed. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. 32-bit packages can be installed on 64-bit systems by appending the architecture designation (``.i686``, ``.i586``, etc.) to the end of the package name. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to update the yum database before executing. reinstall Specifying reinstall=True will use ``yum reinstall`` rather than ``yum install`` for requested packages that are already installed. If a version is specified with the requested package, then ``yum reinstall`` will only be used if the installed version matches the requested version. Works with ``sources`` when the package header of the source can be matched to the name and version of an installed package. .. versionadded:: 2014.7.0 skip_verify Skip the GPG verification check (e.g., ``--nogpgcheck``) downloadonly Only download the packages, do not install. version Install a specific version of the package, e.g. 1.2.3-4.el5. Ignored if "pkgs" or "sources" is passed. .. versionchanged:: 2018.3.0 version can now contain comparison operators (e.g. ``>1.2.3``, ``<=2.0``, etc.) update_holds : False If ``True``, and this function would update the package version, any packages held using the yum/dnf "versionlock" plugin will be unheld so that they can be updated. Otherwise, if this function attempts to update a held package, the held package(s) will be skipped and an error will be raised. .. versionadded:: 2016.11.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. CLI Example: .. code-block:: bash salt '*' pkg.install foo setopt='obsoletes=0,plugins=0' .. versionadded:: 2019.2.0 Repository Options: fromrepo Specify a package repository (or repositories) from which to install. (e.g., ``yum --disablerepo='*' --enablerepo='somerepo'``) enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) disableexcludes Disable exclude from main, for a repo or for everything. (e.g., ``yum --disableexcludes='main'``) .. versionadded:: 2014.7.0 ignore_epoch : False Only used when the version of a package is specified using a comparison operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be ignored when comparing the currently-installed version to the desired version. .. versionadded:: 2018.3.0 Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. A specific version number can be specified by using a single-element dict representing the package and its version. CLI Examples: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4.el5"}]' sources A list of RPM packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' normalize : True Normalize the package name by removing the architecture. This is useful for poorly created packages which might include the architecture as an actual part of the name such as kernel modules which match a specific kernel version. .. code-block:: bash salt -G role:nsd pkg.install gpfs.gplbin-2.6.32-279.31.1.el6.x86_64 normalize=False .. versionadded:: 2014.7.0 diff_attr: If a list of package attributes is specified, returned value will contain them, eg.:: {'<package>': { 'old': { 'version': '<old-version>', 'arch': '<old-arch>'}, 'new': { 'version': '<new-version>', 'arch': '<new-arch>'}}} Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``, ``install_date``, ``install_date_time_t``. If ``all`` is specified, all valid attributes will be returned. .. versionadded:: 2018.3.0 Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} If an attribute list in diff_attr is specified, the dict will also contain any specified attribute, eg.:: {'<package>': { 'old': { 'version': '<old-version>', 'arch': '<old-arch>'}, 'new': { 'version': '<new-version>', 'arch': '<new-arch>'}}} ''' options = _get_options(**kwargs) if salt.utils.data.is_true(refresh): refresh_db(**kwargs) reinstall = salt.utils.data.is_true(reinstall) try: pkg_params, pkg_type = __salt__['pkg_resource.parse_targets']( name, pkgs, sources, saltenv=saltenv, normalize=normalize, **kwargs ) except MinionError as exc: raise CommandExecutionError(exc) if not pkg_params: return {} version_num = kwargs.get('version') diff_attr = kwargs.get('diff_attr') old = list_pkgs(versions_as_list=False, attr=diff_attr) if not downloadonly else list_downloaded() # Use of __context__ means no duplicate work here, just accessing # information already in __context__ from the previous call to list_pkgs() old_as_list = list_pkgs(versions_as_list=True) if not downloadonly else list_downloaded() to_install = [] to_downgrade = [] to_reinstall = [] _available = {} # The above three lists will be populated with tuples containing the # package name and the string being used for this particular package # modification. The reason for this method is that the string we use for # installation, downgrading, or reinstallation will be different than the # package name in a couple cases: # # 1) A specific version is being targeted. In this case the string being # passed to install/downgrade/reinstall will contain the version # information after the package name. # 2) A binary package is being installed via the "sources" param. In this # case the string being passed will be the path to the local copy of # the package in the minion cachedir. # # The reason that we need both items is to be able to modify the installed # version of held packages. if pkg_type == 'repository': has_wildcards = [] has_comparison = [] for pkgname, pkgver in six.iteritems(pkg_params): try: if '*' in pkgver: has_wildcards.append(pkgname) elif pkgver.startswith('<') or pkgver.startswith('>'): has_comparison.append(pkgname) except (TypeError, ValueError): continue _available = AvailablePackages( *has_wildcards + has_comparison, byrepo=False, **kwargs) pkg_params_items = six.iteritems(pkg_params) elif pkg_type == 'advisory': pkg_params_items = [] cur_patches = list_patches() for advisory_id in pkg_params: if advisory_id not in cur_patches: raise CommandExecutionError( 'Advisory id "{0}" not found'.format(advisory_id) ) else: pkg_params_items.append(advisory_id) else: pkg_params_items = [] for pkg_source in pkg_params: if 'lowpkg.bin_pkg_info' in __salt__: rpm_info = __salt__['lowpkg.bin_pkg_info'](pkg_source) else: rpm_info = None if rpm_info is None: log.error( 'pkg.install: Unable to get rpm information for %s. ' 'Version comparisons will be unavailable, and return ' 'data may be inaccurate if reinstall=True.', pkg_source ) pkg_params_items.append([pkg_source]) else: pkg_params_items.append( [rpm_info['name'], pkg_source, rpm_info['version']] ) errors = [] for pkg_item_list in pkg_params_items: if pkg_type == 'repository': pkgname, version_num = pkg_item_list elif pkg_type == 'advisory': pkgname = pkg_item_list version_num = None else: try: pkgname, pkgpath, version_num = pkg_item_list except ValueError: pkgname = None pkgpath = pkg_item_list[0] version_num = None if version_num is None: if pkg_type == 'repository': if reinstall and pkgname in old: to_reinstall.append((pkgname, pkgname)) else: to_install.append((pkgname, pkgname)) elif pkg_type == 'advisory': to_install.append((pkgname, pkgname)) else: to_install.append((pkgname, pkgpath)) else: # If we are installing a package file and not one from the repo, # and version_num is not None, then we can assume that pkgname is # not None, since the only way version_num is not None is if RPM # metadata parsing was successful. if pkg_type == 'repository': # yum/dnf does not support comparison operators. If the version # starts with an equals sign, ignore it. version_num = version_num.lstrip('=') if pkgname in has_comparison: candidates = _available.get(pkgname, []) target = salt.utils.pkg.match_version( version_num, candidates, cmp_func=version_cmp, ignore_epoch=ignore_epoch, ) if target is None: errors.append( 'No version matching \'{0}{1}\' could be found ' '(available: {2})'.format( pkgname, version_num, ', '.join(candidates) if candidates else None ) ) continue else: version_num = target if _yum() == 'yum': # yum install does not support epoch without the arch, and # we won't know what the arch will be when it's not # provided. It could either be the OS architecture, or # 'noarch', and we don't make that distinction in the # pkg.list_pkgs return data. if ignore_epoch is True: version_num = version_num.split(':', 1)[-1] arch = '' try: namepart, archpart = pkgname.rsplit('.', 1) except ValueError: pass else: if archpart in salt.utils.pkg.rpm.ARCHES: arch = '.' + archpart pkgname = namepart if '*' in version_num: # Resolve wildcard matches candidates = _available.get(pkgname, []) match = salt.utils.itertools.fnmatch_multiple(candidates, version_num) if match is not None: version_num = match else: errors.append( 'No version matching \'{0}\' found for package ' '\'{1}\' (available: {2})'.format( version_num, pkgname, ', '.join(candidates) if candidates else 'none' ) ) continue if ignore_epoch is True: pkgstr = '{0}-{1}{2}'.format(pkgname, version_num, arch) else: pkgstr = '{0}-{1}{2}'.format(pkgname, version_num.split(':', 1)[-1], arch) else: pkgstr = pkgpath # Lambda to trim the epoch from the currently-installed version if # no epoch is specified in the specified version cver = old_as_list.get(pkgname, []) if reinstall and cver: for ver in cver: if salt.utils.versions.compare(ver1=version_num, oper='==', ver2=ver, cmp_func=version_cmp, ignore_epoch=ignore_epoch): # This version is already installed, so we need to # reinstall. to_reinstall.append((pkgname, pkgstr)) break else: if not cver: to_install.append((pkgname, pkgstr)) else: for ver in cver: if salt.utils.versions.compare(ver1=version_num, oper='>=', ver2=ver, cmp_func=version_cmp, ignore_epoch=ignore_epoch): to_install.append((pkgname, pkgstr)) break else: if pkgname is not None: if re.match('^kernel(|-devel)$', pkgname): # kernel and kernel-devel support multiple # installs as their paths do not conflict. # Performing a yum/dnf downgrade will be a # no-op so just do an install instead. It will # fail if there are other interdependencies # that have conflicts, and that's OK. We don't # want to force anything, we just want to # properly handle it if someone tries to # install a kernel/kernel-devel of a lower # version than the currently-installed one. # TODO: find a better way to determine if a # package supports multiple installs. to_install.append((pkgname, pkgstr)) else: # None of the currently-installed versions are # greater than the specified version, so this # is a downgrade. to_downgrade.append((pkgname, pkgstr)) def _add_common_args(cmd): ''' DRY function to add args common to all yum/dnf commands ''' cmd.extend(options) if skip_verify: cmd.append('--nogpgcheck') if downloadonly: cmd.append('--downloadonly') try: holds = list_holds(full=False) except SaltInvocationError: holds = [] log.debug( 'Failed to get holds, versionlock plugin is probably not ' 'installed' ) unhold_prevented = [] @contextlib.contextmanager def _temporarily_unhold(pkgs, targets): ''' Temporarily unhold packages that need to be updated. Add any successfully-removed ones (and any packages not in the list of current holds) to the list of targets. ''' to_unhold = {} for pkgname, pkgstr in pkgs: if pkgname in holds: if update_holds: to_unhold[pkgname] = pkgstr else: unhold_prevented.append(pkgname) else: targets.append(pkgstr) if not to_unhold: yield else: log.debug('Unholding packages: %s', ', '.join(to_unhold)) try: # Using list() here for python3 compatibility, dict.keys() no # longer returns a list in python3. unhold_names = list(to_unhold.keys()) for unheld_pkg, outcome in \ six.iteritems(unhold(pkgs=unhold_names)): if outcome['result']: # Package was successfully unheld, add to targets targets.append(to_unhold[unheld_pkg]) else: # Failed to unhold package errors.append(unheld_pkg) yield except Exception as exc: errors.append( 'Error encountered unholding packages {0}: {1}' .format(', '.join(to_unhold), exc) ) finally: hold(pkgs=unhold_names) targets = [] with _temporarily_unhold(to_install, targets): if targets: if pkg_type == 'advisory': targets = ["--advisory={0}".format(t) for t in targets] cmd = ['-y'] if _yum() == 'dnf': cmd.extend(['--best', '--allowerasing']) _add_common_args(cmd) cmd.append('install' if pkg_type != 'advisory' else 'update') cmd.extend(targets) out = _call_yum(cmd, ignore_retcode=False, redirect_stderr=True) if out['retcode'] != 0: errors.append(out['stdout']) targets = [] with _temporarily_unhold(to_downgrade, targets): if targets: cmd = ['-y'] _add_common_args(cmd) cmd.append('downgrade') cmd.extend(targets) out = _call_yum(cmd) if out['retcode'] != 0: errors.append(out['stdout']) targets = [] with _temporarily_unhold(to_reinstall, targets): if targets: cmd = ['-y'] _add_common_args(cmd) cmd.append('reinstall') cmd.extend(targets) out = _call_yum(cmd) if out['retcode'] != 0: errors.append(out['stdout']) __context__.pop('pkg.list_pkgs', None) new = list_pkgs(versions_as_list=False, attr=diff_attr) if not downloadonly else list_downloaded() ret = salt.utils.data.compare_dicts(old, new) for pkgname, _ in to_reinstall: if pkgname not in ret or pkgname in old: ret.update({pkgname: {'old': old.get(pkgname, ''), 'new': new.get(pkgname, '')}}) if unhold_prevented: errors.append( 'The following package(s) could not be updated because they are ' 'being held: {0}. Set \'update_holds\' to True to temporarily ' 'unhold these packages so that they can be updated.'.format( ', '.join(unhold_prevented) ) ) if errors: raise CommandExecutionError( 'Error occurred installing{0} package(s)'.format( '/reinstalling' if to_reinstall else '' ), info={'errors': errors, 'changes': ret} ) return ret
python
def install(name=None, refresh=False, skip_verify=False, pkgs=None, sources=None, downloadonly=False, reinstall=False, normalize=True, update_holds=False, saltenv='base', ignore_epoch=False, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Install the passed package(s), add refresh=True to clean the yum database before package is installed. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. 32-bit packages can be installed on 64-bit systems by appending the architecture designation (``.i686``, ``.i586``, etc.) to the end of the package name. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to update the yum database before executing. reinstall Specifying reinstall=True will use ``yum reinstall`` rather than ``yum install`` for requested packages that are already installed. If a version is specified with the requested package, then ``yum reinstall`` will only be used if the installed version matches the requested version. Works with ``sources`` when the package header of the source can be matched to the name and version of an installed package. .. versionadded:: 2014.7.0 skip_verify Skip the GPG verification check (e.g., ``--nogpgcheck``) downloadonly Only download the packages, do not install. version Install a specific version of the package, e.g. 1.2.3-4.el5. Ignored if "pkgs" or "sources" is passed. .. versionchanged:: 2018.3.0 version can now contain comparison operators (e.g. ``>1.2.3``, ``<=2.0``, etc.) update_holds : False If ``True``, and this function would update the package version, any packages held using the yum/dnf "versionlock" plugin will be unheld so that they can be updated. Otherwise, if this function attempts to update a held package, the held package(s) will be skipped and an error will be raised. .. versionadded:: 2016.11.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. CLI Example: .. code-block:: bash salt '*' pkg.install foo setopt='obsoletes=0,plugins=0' .. versionadded:: 2019.2.0 Repository Options: fromrepo Specify a package repository (or repositories) from which to install. (e.g., ``yum --disablerepo='*' --enablerepo='somerepo'``) enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) disableexcludes Disable exclude from main, for a repo or for everything. (e.g., ``yum --disableexcludes='main'``) .. versionadded:: 2014.7.0 ignore_epoch : False Only used when the version of a package is specified using a comparison operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be ignored when comparing the currently-installed version to the desired version. .. versionadded:: 2018.3.0 Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. A specific version number can be specified by using a single-element dict representing the package and its version. CLI Examples: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4.el5"}]' sources A list of RPM packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' normalize : True Normalize the package name by removing the architecture. This is useful for poorly created packages which might include the architecture as an actual part of the name such as kernel modules which match a specific kernel version. .. code-block:: bash salt -G role:nsd pkg.install gpfs.gplbin-2.6.32-279.31.1.el6.x86_64 normalize=False .. versionadded:: 2014.7.0 diff_attr: If a list of package attributes is specified, returned value will contain them, eg.:: {'<package>': { 'old': { 'version': '<old-version>', 'arch': '<old-arch>'}, 'new': { 'version': '<new-version>', 'arch': '<new-arch>'}}} Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``, ``install_date``, ``install_date_time_t``. If ``all`` is specified, all valid attributes will be returned. .. versionadded:: 2018.3.0 Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} If an attribute list in diff_attr is specified, the dict will also contain any specified attribute, eg.:: {'<package>': { 'old': { 'version': '<old-version>', 'arch': '<old-arch>'}, 'new': { 'version': '<new-version>', 'arch': '<new-arch>'}}} ''' options = _get_options(**kwargs) if salt.utils.data.is_true(refresh): refresh_db(**kwargs) reinstall = salt.utils.data.is_true(reinstall) try: pkg_params, pkg_type = __salt__['pkg_resource.parse_targets']( name, pkgs, sources, saltenv=saltenv, normalize=normalize, **kwargs ) except MinionError as exc: raise CommandExecutionError(exc) if not pkg_params: return {} version_num = kwargs.get('version') diff_attr = kwargs.get('diff_attr') old = list_pkgs(versions_as_list=False, attr=diff_attr) if not downloadonly else list_downloaded() # Use of __context__ means no duplicate work here, just accessing # information already in __context__ from the previous call to list_pkgs() old_as_list = list_pkgs(versions_as_list=True) if not downloadonly else list_downloaded() to_install = [] to_downgrade = [] to_reinstall = [] _available = {} # The above three lists will be populated with tuples containing the # package name and the string being used for this particular package # modification. The reason for this method is that the string we use for # installation, downgrading, or reinstallation will be different than the # package name in a couple cases: # # 1) A specific version is being targeted. In this case the string being # passed to install/downgrade/reinstall will contain the version # information after the package name. # 2) A binary package is being installed via the "sources" param. In this # case the string being passed will be the path to the local copy of # the package in the minion cachedir. # # The reason that we need both items is to be able to modify the installed # version of held packages. if pkg_type == 'repository': has_wildcards = [] has_comparison = [] for pkgname, pkgver in six.iteritems(pkg_params): try: if '*' in pkgver: has_wildcards.append(pkgname) elif pkgver.startswith('<') or pkgver.startswith('>'): has_comparison.append(pkgname) except (TypeError, ValueError): continue _available = AvailablePackages( *has_wildcards + has_comparison, byrepo=False, **kwargs) pkg_params_items = six.iteritems(pkg_params) elif pkg_type == 'advisory': pkg_params_items = [] cur_patches = list_patches() for advisory_id in pkg_params: if advisory_id not in cur_patches: raise CommandExecutionError( 'Advisory id "{0}" not found'.format(advisory_id) ) else: pkg_params_items.append(advisory_id) else: pkg_params_items = [] for pkg_source in pkg_params: if 'lowpkg.bin_pkg_info' in __salt__: rpm_info = __salt__['lowpkg.bin_pkg_info'](pkg_source) else: rpm_info = None if rpm_info is None: log.error( 'pkg.install: Unable to get rpm information for %s. ' 'Version comparisons will be unavailable, and return ' 'data may be inaccurate if reinstall=True.', pkg_source ) pkg_params_items.append([pkg_source]) else: pkg_params_items.append( [rpm_info['name'], pkg_source, rpm_info['version']] ) errors = [] for pkg_item_list in pkg_params_items: if pkg_type == 'repository': pkgname, version_num = pkg_item_list elif pkg_type == 'advisory': pkgname = pkg_item_list version_num = None else: try: pkgname, pkgpath, version_num = pkg_item_list except ValueError: pkgname = None pkgpath = pkg_item_list[0] version_num = None if version_num is None: if pkg_type == 'repository': if reinstall and pkgname in old: to_reinstall.append((pkgname, pkgname)) else: to_install.append((pkgname, pkgname)) elif pkg_type == 'advisory': to_install.append((pkgname, pkgname)) else: to_install.append((pkgname, pkgpath)) else: # If we are installing a package file and not one from the repo, # and version_num is not None, then we can assume that pkgname is # not None, since the only way version_num is not None is if RPM # metadata parsing was successful. if pkg_type == 'repository': # yum/dnf does not support comparison operators. If the version # starts with an equals sign, ignore it. version_num = version_num.lstrip('=') if pkgname in has_comparison: candidates = _available.get(pkgname, []) target = salt.utils.pkg.match_version( version_num, candidates, cmp_func=version_cmp, ignore_epoch=ignore_epoch, ) if target is None: errors.append( 'No version matching \'{0}{1}\' could be found ' '(available: {2})'.format( pkgname, version_num, ', '.join(candidates) if candidates else None ) ) continue else: version_num = target if _yum() == 'yum': # yum install does not support epoch without the arch, and # we won't know what the arch will be when it's not # provided. It could either be the OS architecture, or # 'noarch', and we don't make that distinction in the # pkg.list_pkgs return data. if ignore_epoch is True: version_num = version_num.split(':', 1)[-1] arch = '' try: namepart, archpart = pkgname.rsplit('.', 1) except ValueError: pass else: if archpart in salt.utils.pkg.rpm.ARCHES: arch = '.' + archpart pkgname = namepart if '*' in version_num: # Resolve wildcard matches candidates = _available.get(pkgname, []) match = salt.utils.itertools.fnmatch_multiple(candidates, version_num) if match is not None: version_num = match else: errors.append( 'No version matching \'{0}\' found for package ' '\'{1}\' (available: {2})'.format( version_num, pkgname, ', '.join(candidates) if candidates else 'none' ) ) continue if ignore_epoch is True: pkgstr = '{0}-{1}{2}'.format(pkgname, version_num, arch) else: pkgstr = '{0}-{1}{2}'.format(pkgname, version_num.split(':', 1)[-1], arch) else: pkgstr = pkgpath # Lambda to trim the epoch from the currently-installed version if # no epoch is specified in the specified version cver = old_as_list.get(pkgname, []) if reinstall and cver: for ver in cver: if salt.utils.versions.compare(ver1=version_num, oper='==', ver2=ver, cmp_func=version_cmp, ignore_epoch=ignore_epoch): # This version is already installed, so we need to # reinstall. to_reinstall.append((pkgname, pkgstr)) break else: if not cver: to_install.append((pkgname, pkgstr)) else: for ver in cver: if salt.utils.versions.compare(ver1=version_num, oper='>=', ver2=ver, cmp_func=version_cmp, ignore_epoch=ignore_epoch): to_install.append((pkgname, pkgstr)) break else: if pkgname is not None: if re.match('^kernel(|-devel)$', pkgname): # kernel and kernel-devel support multiple # installs as their paths do not conflict. # Performing a yum/dnf downgrade will be a # no-op so just do an install instead. It will # fail if there are other interdependencies # that have conflicts, and that's OK. We don't # want to force anything, we just want to # properly handle it if someone tries to # install a kernel/kernel-devel of a lower # version than the currently-installed one. # TODO: find a better way to determine if a # package supports multiple installs. to_install.append((pkgname, pkgstr)) else: # None of the currently-installed versions are # greater than the specified version, so this # is a downgrade. to_downgrade.append((pkgname, pkgstr)) def _add_common_args(cmd): ''' DRY function to add args common to all yum/dnf commands ''' cmd.extend(options) if skip_verify: cmd.append('--nogpgcheck') if downloadonly: cmd.append('--downloadonly') try: holds = list_holds(full=False) except SaltInvocationError: holds = [] log.debug( 'Failed to get holds, versionlock plugin is probably not ' 'installed' ) unhold_prevented = [] @contextlib.contextmanager def _temporarily_unhold(pkgs, targets): ''' Temporarily unhold packages that need to be updated. Add any successfully-removed ones (and any packages not in the list of current holds) to the list of targets. ''' to_unhold = {} for pkgname, pkgstr in pkgs: if pkgname in holds: if update_holds: to_unhold[pkgname] = pkgstr else: unhold_prevented.append(pkgname) else: targets.append(pkgstr) if not to_unhold: yield else: log.debug('Unholding packages: %s', ', '.join(to_unhold)) try: # Using list() here for python3 compatibility, dict.keys() no # longer returns a list in python3. unhold_names = list(to_unhold.keys()) for unheld_pkg, outcome in \ six.iteritems(unhold(pkgs=unhold_names)): if outcome['result']: # Package was successfully unheld, add to targets targets.append(to_unhold[unheld_pkg]) else: # Failed to unhold package errors.append(unheld_pkg) yield except Exception as exc: errors.append( 'Error encountered unholding packages {0}: {1}' .format(', '.join(to_unhold), exc) ) finally: hold(pkgs=unhold_names) targets = [] with _temporarily_unhold(to_install, targets): if targets: if pkg_type == 'advisory': targets = ["--advisory={0}".format(t) for t in targets] cmd = ['-y'] if _yum() == 'dnf': cmd.extend(['--best', '--allowerasing']) _add_common_args(cmd) cmd.append('install' if pkg_type != 'advisory' else 'update') cmd.extend(targets) out = _call_yum(cmd, ignore_retcode=False, redirect_stderr=True) if out['retcode'] != 0: errors.append(out['stdout']) targets = [] with _temporarily_unhold(to_downgrade, targets): if targets: cmd = ['-y'] _add_common_args(cmd) cmd.append('downgrade') cmd.extend(targets) out = _call_yum(cmd) if out['retcode'] != 0: errors.append(out['stdout']) targets = [] with _temporarily_unhold(to_reinstall, targets): if targets: cmd = ['-y'] _add_common_args(cmd) cmd.append('reinstall') cmd.extend(targets) out = _call_yum(cmd) if out['retcode'] != 0: errors.append(out['stdout']) __context__.pop('pkg.list_pkgs', None) new = list_pkgs(versions_as_list=False, attr=diff_attr) if not downloadonly else list_downloaded() ret = salt.utils.data.compare_dicts(old, new) for pkgname, _ in to_reinstall: if pkgname not in ret or pkgname in old: ret.update({pkgname: {'old': old.get(pkgname, ''), 'new': new.get(pkgname, '')}}) if unhold_prevented: errors.append( 'The following package(s) could not be updated because they are ' 'being held: {0}. Set \'update_holds\' to True to temporarily ' 'unhold these packages so that they can be updated.'.format( ', '.join(unhold_prevented) ) ) if errors: raise CommandExecutionError( 'Error occurred installing{0} package(s)'.format( '/reinstalling' if to_reinstall else '' ), info={'errors': errors, 'changes': ret} ) return ret
[ "def", "install", "(", "name", "=", "None", ",", "refresh", "=", "False", ",", "skip_verify", "=", "False", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "downloadonly", "=", "False", ",", "reinstall", "=", "False", ",", "normalize", "=",...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Install the passed package(s), add refresh=True to clean the yum database before package is installed. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. 32-bit packages can be installed on 64-bit systems by appending the architecture designation (``.i686``, ``.i586``, etc.) to the end of the package name. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to update the yum database before executing. reinstall Specifying reinstall=True will use ``yum reinstall`` rather than ``yum install`` for requested packages that are already installed. If a version is specified with the requested package, then ``yum reinstall`` will only be used if the installed version matches the requested version. Works with ``sources`` when the package header of the source can be matched to the name and version of an installed package. .. versionadded:: 2014.7.0 skip_verify Skip the GPG verification check (e.g., ``--nogpgcheck``) downloadonly Only download the packages, do not install. version Install a specific version of the package, e.g. 1.2.3-4.el5. Ignored if "pkgs" or "sources" is passed. .. versionchanged:: 2018.3.0 version can now contain comparison operators (e.g. ``>1.2.3``, ``<=2.0``, etc.) update_holds : False If ``True``, and this function would update the package version, any packages held using the yum/dnf "versionlock" plugin will be unheld so that they can be updated. Otherwise, if this function attempts to update a held package, the held package(s) will be skipped and an error will be raised. .. versionadded:: 2016.11.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. CLI Example: .. code-block:: bash salt '*' pkg.install foo setopt='obsoletes=0,plugins=0' .. versionadded:: 2019.2.0 Repository Options: fromrepo Specify a package repository (or repositories) from which to install. (e.g., ``yum --disablerepo='*' --enablerepo='somerepo'``) enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) disableexcludes Disable exclude from main, for a repo or for everything. (e.g., ``yum --disableexcludes='main'``) .. versionadded:: 2014.7.0 ignore_epoch : False Only used when the version of a package is specified using a comparison operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be ignored when comparing the currently-installed version to the desired version. .. versionadded:: 2018.3.0 Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. A specific version number can be specified by using a single-element dict representing the package and its version. CLI Examples: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4.el5"}]' sources A list of RPM packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' normalize : True Normalize the package name by removing the architecture. This is useful for poorly created packages which might include the architecture as an actual part of the name such as kernel modules which match a specific kernel version. .. code-block:: bash salt -G role:nsd pkg.install gpfs.gplbin-2.6.32-279.31.1.el6.x86_64 normalize=False .. versionadded:: 2014.7.0 diff_attr: If a list of package attributes is specified, returned value will contain them, eg.:: {'<package>': { 'old': { 'version': '<old-version>', 'arch': '<old-arch>'}, 'new': { 'version': '<new-version>', 'arch': '<new-arch>'}}} Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``, ``install_date``, ``install_date_time_t``. If ``all`` is specified, all valid attributes will be returned. .. versionadded:: 2018.3.0 Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} If an attribute list in diff_attr is specified, the dict will also contain any specified attribute, eg.:: {'<package>': { 'old': { 'version': '<old-version>', 'arch': '<old-arch>'}, 'new': { 'version': '<new-version>', 'arch': '<new-arch>'}}}
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "12", "2016", ".", "3", ".", "3", "2016", ".", "11", ".", "0", "On", "minions", "running", "systemd", ">", "=", "205", "systemd", "-", "run", "(", "1", ")", "_", "is", "now", "used", "to", "i...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L1158-L1720
train
saltstack/salt
salt/modules/yumpkg.py
upgrade
def upgrade(name=None, pkgs=None, refresh=True, skip_verify=False, normalize=True, minimal=False, obsoletes=True, **kwargs): ''' Run a full system upgrade (a ``yum upgrade`` or ``dnf upgrade``), or upgrade specified packages. If the packages aren't installed, they will not be installed. .. versionchanged:: 2014.7.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html .. versionchanged:: 2019.2.0 Added ``obsoletes`` and ``minimal`` arguments Returns a dictionary containing the changes: .. code-block:: python {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade salt '*' pkg.upgrade name=openssl Repository Options: fromrepo Specify a package repository (or repositories) from which to install. (e.g., ``yum --disablerepo='*' --enablerepo='somerepo'``) enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) disableexcludes Disable exclude from main, for a repo or for everything. (e.g., ``yum --disableexcludes='main'``) .. versionadded:: 2014.7 name The name of the package to be upgraded. Note that this parameter is ignored if "pkgs" is passed. 32-bit packages can be upgraded on 64-bit systems by appending the architecture designation (``.i686``, ``.i586``, etc.) to the end of the package name. Warning: if you forget 'name=' and run pkg.upgrade openssl, ALL packages are upgraded. This will be addressed in next releases. CLI Example: .. code-block:: bash salt '*' pkg.upgrade name=openssl .. versionadded:: 2016.3.0 pkgs A list of packages to upgrade from a software repository. Must be passed as a python list. A specific version number can be specified by using a single-element dict representing the package and its version. If the package was not already installed on the system, it will not be installed. CLI Examples: .. code-block:: bash salt '*' pkg.upgrade pkgs='["foo", "bar"]' salt '*' pkg.upgrade pkgs='["foo", {"bar": "1.2.3-4.el5"}]' .. versionadded:: 2016.3.0 normalize : True Normalize the package name by removing the architecture. This is useful for poorly created packages which might include the architecture as an actual part of the name such as kernel modules which match a specific kernel version. .. code-block:: bash salt -G role:nsd pkg.upgrade gpfs.gplbin-2.6.32-279.31.1.el6.x86_64 normalize=False .. versionadded:: 2016.3.0 minimal : False Use upgrade-minimal instead of upgrade (e.g., ``yum upgrade-minimal``) Goes to the 'newest' package match which fixes a problem that affects your system. .. code-block:: bash salt '*' pkg.upgrade minimal=True .. versionadded:: 2019.2.0 obsoletes : True Controls wether yum/dnf should take obsoletes into account and remove them. If set to ``False`` yum will use ``update`` instead of ``upgrade`` and dnf will be run with ``--obsoletes=False`` .. code-block:: bash salt '*' pkg.upgrade obsoletes=False .. versionadded:: 2019.2.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 .. note:: To add extra arguments to the ``yum upgrade`` command, pass them as key word arguments. For arguments without assignments, pass ``True`` .. code-block:: bash salt '*' pkg.upgrade security=True exclude='kernel*' ''' options = _get_options(get_extra_options=True, **kwargs) if salt.utils.data.is_true(refresh): refresh_db(**kwargs) old = list_pkgs() targets = [] if name or pkgs: try: pkg_params = __salt__['pkg_resource.parse_targets']( name=name, pkgs=pkgs, sources=None, normalize=normalize, **kwargs)[0] except MinionError as exc: raise CommandExecutionError(exc) if pkg_params: # Calling list.extend() on a dict will extend it using the # dictionary's keys. targets.extend(pkg_params) cmd = ['--quiet', '-y'] cmd.extend(options) if skip_verify: cmd.append('--nogpgcheck') if obsoletes: cmd.append('upgrade' if not minimal else 'upgrade-minimal') else: # do not force the removal of obsolete packages if _yum() == 'dnf': # for dnf we can just disable obsoletes cmd.append('--obsoletes=False') cmd.append('upgrade' if not minimal else 'upgrade-minimal') else: # for yum we have to use update instead of upgrade cmd.append('update' if not minimal else 'update-minimal') cmd.extend(targets) result = _call_yum(cmd) __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, refresh=True, skip_verify=False, normalize=True, minimal=False, obsoletes=True, **kwargs): ''' Run a full system upgrade (a ``yum upgrade`` or ``dnf upgrade``), or upgrade specified packages. If the packages aren't installed, they will not be installed. .. versionchanged:: 2014.7.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html .. versionchanged:: 2019.2.0 Added ``obsoletes`` and ``minimal`` arguments Returns a dictionary containing the changes: .. code-block:: python {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade salt '*' pkg.upgrade name=openssl Repository Options: fromrepo Specify a package repository (or repositories) from which to install. (e.g., ``yum --disablerepo='*' --enablerepo='somerepo'``) enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) disableexcludes Disable exclude from main, for a repo or for everything. (e.g., ``yum --disableexcludes='main'``) .. versionadded:: 2014.7 name The name of the package to be upgraded. Note that this parameter is ignored if "pkgs" is passed. 32-bit packages can be upgraded on 64-bit systems by appending the architecture designation (``.i686``, ``.i586``, etc.) to the end of the package name. Warning: if you forget 'name=' and run pkg.upgrade openssl, ALL packages are upgraded. This will be addressed in next releases. CLI Example: .. code-block:: bash salt '*' pkg.upgrade name=openssl .. versionadded:: 2016.3.0 pkgs A list of packages to upgrade from a software repository. Must be passed as a python list. A specific version number can be specified by using a single-element dict representing the package and its version. If the package was not already installed on the system, it will not be installed. CLI Examples: .. code-block:: bash salt '*' pkg.upgrade pkgs='["foo", "bar"]' salt '*' pkg.upgrade pkgs='["foo", {"bar": "1.2.3-4.el5"}]' .. versionadded:: 2016.3.0 normalize : True Normalize the package name by removing the architecture. This is useful for poorly created packages which might include the architecture as an actual part of the name such as kernel modules which match a specific kernel version. .. code-block:: bash salt -G role:nsd pkg.upgrade gpfs.gplbin-2.6.32-279.31.1.el6.x86_64 normalize=False .. versionadded:: 2016.3.0 minimal : False Use upgrade-minimal instead of upgrade (e.g., ``yum upgrade-minimal``) Goes to the 'newest' package match which fixes a problem that affects your system. .. code-block:: bash salt '*' pkg.upgrade minimal=True .. versionadded:: 2019.2.0 obsoletes : True Controls wether yum/dnf should take obsoletes into account and remove them. If set to ``False`` yum will use ``update`` instead of ``upgrade`` and dnf will be run with ``--obsoletes=False`` .. code-block:: bash salt '*' pkg.upgrade obsoletes=False .. versionadded:: 2019.2.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 .. note:: To add extra arguments to the ``yum upgrade`` command, pass them as key word arguments. For arguments without assignments, pass ``True`` .. code-block:: bash salt '*' pkg.upgrade security=True exclude='kernel*' ''' options = _get_options(get_extra_options=True, **kwargs) if salt.utils.data.is_true(refresh): refresh_db(**kwargs) old = list_pkgs() targets = [] if name or pkgs: try: pkg_params = __salt__['pkg_resource.parse_targets']( name=name, pkgs=pkgs, sources=None, normalize=normalize, **kwargs)[0] except MinionError as exc: raise CommandExecutionError(exc) if pkg_params: # Calling list.extend() on a dict will extend it using the # dictionary's keys. targets.extend(pkg_params) cmd = ['--quiet', '-y'] cmd.extend(options) if skip_verify: cmd.append('--nogpgcheck') if obsoletes: cmd.append('upgrade' if not minimal else 'upgrade-minimal') else: # do not force the removal of obsolete packages if _yum() == 'dnf': # for dnf we can just disable obsoletes cmd.append('--obsoletes=False') cmd.append('upgrade' if not minimal else 'upgrade-minimal') else: # for yum we have to use update instead of upgrade cmd.append('update' if not minimal else 'update-minimal') cmd.extend(targets) result = _call_yum(cmd) __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", ",", "refresh", "=", "True", ",", "skip_verify", "=", "False", ",", "normalize", "=", "True", ",", "minimal", "=", "False", ",", "obsoletes", "=", "True", ",", "*", "*", "kwargs", ...
Run a full system upgrade (a ``yum upgrade`` or ``dnf upgrade``), or upgrade specified packages. If the packages aren't installed, they will not be installed. .. versionchanged:: 2014.7.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html .. versionchanged:: 2019.2.0 Added ``obsoletes`` and ``minimal`` arguments Returns a dictionary containing the changes: .. code-block:: python {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade salt '*' pkg.upgrade name=openssl Repository Options: fromrepo Specify a package repository (or repositories) from which to install. (e.g., ``yum --disablerepo='*' --enablerepo='somerepo'``) enablerepo (ignored if ``fromrepo`` is specified) Specify a disabled package repository (or repositories) to enable. (e.g., ``yum --enablerepo='somerepo'``) disablerepo (ignored if ``fromrepo`` is specified) Specify an enabled package repository (or repositories) to disable. (e.g., ``yum --disablerepo='somerepo'``) disableexcludes Disable exclude from main, for a repo or for everything. (e.g., ``yum --disableexcludes='main'``) .. versionadded:: 2014.7 name The name of the package to be upgraded. Note that this parameter is ignored if "pkgs" is passed. 32-bit packages can be upgraded on 64-bit systems by appending the architecture designation (``.i686``, ``.i586``, etc.) to the end of the package name. Warning: if you forget 'name=' and run pkg.upgrade openssl, ALL packages are upgraded. This will be addressed in next releases. CLI Example: .. code-block:: bash salt '*' pkg.upgrade name=openssl .. versionadded:: 2016.3.0 pkgs A list of packages to upgrade from a software repository. Must be passed as a python list. A specific version number can be specified by using a single-element dict representing the package and its version. If the package was not already installed on the system, it will not be installed. CLI Examples: .. code-block:: bash salt '*' pkg.upgrade pkgs='["foo", "bar"]' salt '*' pkg.upgrade pkgs='["foo", {"bar": "1.2.3-4.el5"}]' .. versionadded:: 2016.3.0 normalize : True Normalize the package name by removing the architecture. This is useful for poorly created packages which might include the architecture as an actual part of the name such as kernel modules which match a specific kernel version. .. code-block:: bash salt -G role:nsd pkg.upgrade gpfs.gplbin-2.6.32-279.31.1.el6.x86_64 normalize=False .. versionadded:: 2016.3.0 minimal : False Use upgrade-minimal instead of upgrade (e.g., ``yum upgrade-minimal``) Goes to the 'newest' package match which fixes a problem that affects your system. .. code-block:: bash salt '*' pkg.upgrade minimal=True .. versionadded:: 2019.2.0 obsoletes : True Controls wether yum/dnf should take obsoletes into account and remove them. If set to ``False`` yum will use ``update`` instead of ``upgrade`` and dnf will be run with ``--obsoletes=False`` .. code-block:: bash salt '*' pkg.upgrade obsoletes=False .. versionadded:: 2019.2.0 setopt A comma-separated or Python list of key=value options. This list will be expanded and ``--setopt`` prepended to each in the yum/dnf command that is run. .. versionadded:: 2019.2.0 .. note:: To add extra arguments to the ``yum upgrade`` command, pass them as key word arguments. For arguments without assignments, pass ``True`` .. code-block:: bash salt '*' pkg.upgrade security=True exclude='kernel*'
[ "Run", "a", "full", "system", "upgrade", "(", "a", "yum", "upgrade", "or", "dnf", "upgrade", ")", "or", "upgrade", "specified", "packages", ".", "If", "the", "packages", "aren", "t", "installed", "they", "will", "not", "be", "installed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L1723-L1923
train
saltstack/salt
salt/modules/yumpkg.py
update
def update(name=None, pkgs=None, refresh=True, skip_verify=False, normalize=True, minimal=False, obsoletes=False, **kwargs): ''' .. versionadded:: 2019.2.0 Calls :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` with ``obsoletes=False``. Mirrors the CLI behavior of ``yum update``. See :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` for further documentation. .. code-block:: bash salt '*' pkg.update ''' return upgrade(name, pkgs, refresh, skip_verify, normalize, minimal, obsoletes, **kwargs)
python
def update(name=None, pkgs=None, refresh=True, skip_verify=False, normalize=True, minimal=False, obsoletes=False, **kwargs): ''' .. versionadded:: 2019.2.0 Calls :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` with ``obsoletes=False``. Mirrors the CLI behavior of ``yum update``. See :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` for further documentation. .. code-block:: bash salt '*' pkg.update ''' return upgrade(name, pkgs, refresh, skip_verify, normalize, minimal, obsoletes, **kwargs)
[ "def", "update", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "refresh", "=", "True", ",", "skip_verify", "=", "False", ",", "normalize", "=", "True", ",", "minimal", "=", "False", ",", "obsoletes", "=", "False", ",", "*", "*", "kwargs", ...
.. versionadded:: 2019.2.0 Calls :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` with ``obsoletes=False``. Mirrors the CLI behavior of ``yum update``. See :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` for further documentation. .. code-block:: bash salt '*' pkg.update
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L1926-L1946
train
saltstack/salt
salt/modules/yumpkg.py
remove
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=W0613 ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Remove packages name The name of the package to be removed 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 = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] except MinionError as exc: raise CommandExecutionError(exc) old = list_pkgs() targets = [] for target in pkg_params: # Check if package version set to be removed is actually installed: # old[target] contains a comma-separated list of installed versions if target in old and not pkg_params[target]: targets.append(target) elif target in old and pkg_params[target] in old[target].split(','): arch = '' pkgname = target try: namepart, archpart = target.rsplit('.', 1) except ValueError: pass else: if archpart in salt.utils.pkg.rpm.ARCHES: arch = '.' + archpart pkgname = namepart targets.append('{0}-{1}{2}'.format(pkgname, pkg_params[target], arch)) if not targets: return {} out = _call_yum(['-y', 'remove'] + targets) 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( 'Error occurred removing package(s)', info={'errors': errors, 'changes': ret} ) return ret
python
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=W0613 ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Remove packages name The name of the package to be removed 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 = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] except MinionError as exc: raise CommandExecutionError(exc) old = list_pkgs() targets = [] for target in pkg_params: # Check if package version set to be removed is actually installed: # old[target] contains a comma-separated list of installed versions if target in old and not pkg_params[target]: targets.append(target) elif target in old and pkg_params[target] in old[target].split(','): arch = '' pkgname = target try: namepart, archpart = target.rsplit('.', 1) except ValueError: pass else: if archpart in salt.utils.pkg.rpm.ARCHES: arch = '.' + archpart pkgname = namepart targets.append('{0}-{1}{2}'.format(pkgname, pkg_params[target], arch)) if not targets: return {} out = _call_yum(['-y', 'remove'] + targets) 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( 'Error occurred removing package(s)', info={'errors': errors, 'changes': ret} ) return ret
[ "def", "remove", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "try", ":", "pkg_params", "=", "__salt__", "[", "'pkg_resource.parse_targets'", "]", "(", "name", ",", "pkgs", ")", "[", "0...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Remove packages name The name of the package to be removed 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"]'
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "12", "2016", ".", "3", ".", "3", "2016", ".", "11", ".", "0", "On", "minions", "running", "systemd", ">", "=", "205", "systemd", "-", "run", "(", "1", ")", "_", "is", "now", "used", "to", "i...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L1949-L2033
train
saltstack/salt
salt/modules/yumpkg.py
hold
def hold(name=None, pkgs=None, sources=None, normalize=True, **kwargs): # pylint: disable=W0613 ''' .. versionadded:: 2014.7.0 Version-lock packages .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` name The name of the package to be held. Multiple Package Options: pkgs A list of packages to hold. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.hold <package name> salt '*' pkg.hold pkgs='["foo", "bar"]' ''' _check_versionlock() if not name and not pkgs and not sources: raise SaltInvocationError( 'One of name, pkgs, or sources must be specified.' ) if pkgs and sources: raise SaltInvocationError( 'Only one of pkgs or sources can be specified.' ) targets = [] if pkgs: targets.extend(pkgs) elif sources: for source in sources: targets.append(next(six.iterkeys(source))) else: targets.append(name) current_locks = list_holds(full=False) ret = {} for target in targets: if isinstance(target, dict): target = next(six.iterkeys(target)) ret[target] = {'name': target, 'changes': {}, 'result': False, 'comment': ''} if target not in current_locks: if 'test' in __opts__ and __opts__['test']: ret[target].update(result=None) ret[target]['comment'] = ('Package {0} is set to be held.' .format(target)) else: out = _call_yum(['versionlock', target]) if out['retcode'] == 0: ret[target].update(result=True) ret[target]['comment'] = ('Package {0} is now being held.' .format(target)) ret[target]['changes']['new'] = 'hold' ret[target]['changes']['old'] = '' else: ret[target]['comment'] = ('Package {0} was unable to be held.' .format(target)) else: ret[target].update(result=True) ret[target]['comment'] = ('Package {0} is already set to be held.' .format(target)) return ret
python
def hold(name=None, pkgs=None, sources=None, normalize=True, **kwargs): # pylint: disable=W0613 ''' .. versionadded:: 2014.7.0 Version-lock packages .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` name The name of the package to be held. Multiple Package Options: pkgs A list of packages to hold. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.hold <package name> salt '*' pkg.hold pkgs='["foo", "bar"]' ''' _check_versionlock() if not name and not pkgs and not sources: raise SaltInvocationError( 'One of name, pkgs, or sources must be specified.' ) if pkgs and sources: raise SaltInvocationError( 'Only one of pkgs or sources can be specified.' ) targets = [] if pkgs: targets.extend(pkgs) elif sources: for source in sources: targets.append(next(six.iterkeys(source))) else: targets.append(name) current_locks = list_holds(full=False) ret = {} for target in targets: if isinstance(target, dict): target = next(six.iterkeys(target)) ret[target] = {'name': target, 'changes': {}, 'result': False, 'comment': ''} if target not in current_locks: if 'test' in __opts__ and __opts__['test']: ret[target].update(result=None) ret[target]['comment'] = ('Package {0} is set to be held.' .format(target)) else: out = _call_yum(['versionlock', target]) if out['retcode'] == 0: ret[target].update(result=True) ret[target]['comment'] = ('Package {0} is now being held.' .format(target)) ret[target]['changes']['new'] = 'hold' ret[target]['changes']['old'] = '' else: ret[target]['comment'] = ('Package {0} was unable to be held.' .format(target)) else: ret[target].update(result=True) ret[target]['comment'] = ('Package {0} is already set to be held.' .format(target)) return ret
[ "def", "hold", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "normalize", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "_check_versionlock", "(", ")", "if", "not", "name", "and", "no...
.. versionadded:: 2014.7.0 Version-lock packages .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` name The name of the package to be held. Multiple Package Options: pkgs A list of packages to hold. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.hold <package name> salt '*' pkg.hold pkgs='["foo", "bar"]'
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2081-L2164
train
saltstack/salt
salt/modules/yumpkg.py
unhold
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 ''' .. versionadded:: 2014.7.0 Remove version locks .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` name The name of the package to be unheld Multiple Package Options: pkgs A list of packages to unhold. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.unhold <package name> salt '*' pkg.unhold pkgs='["foo", "bar"]' ''' _check_versionlock() if not name and not pkgs and not sources: raise SaltInvocationError( 'One of name, pkgs, or sources must be specified.' ) if pkgs and sources: raise SaltInvocationError( 'Only one of pkgs or sources can be specified.' ) targets = [] if pkgs: for pkg in salt.utils.data.repack_dictlist(pkgs): targets.append(pkg) elif sources: for source in sources: targets.append(next(iter(source))) else: targets.append(name) # Yum's versionlock plugin doesn't support passing just the package name # when removing a lock, so we need to get the full list and then use # fnmatch below to find the match. current_locks = list_holds(full=_yum() == 'yum') ret = {} for target in targets: if isinstance(target, dict): target = next(six.iterkeys(target)) ret[target] = {'name': target, 'changes': {}, 'result': False, 'comment': ''} if _yum() == 'dnf': search_locks = [x for x in current_locks if x == target] else: # To accommodate yum versionlock's lack of support for removing # locks using just the package name, we have to use fnmatch to do # glob matching on the target name, and then for each matching # expression double-check that the package name (obtained via # _get_hold()) matches the targeted package. search_locks = [ x for x in current_locks if fnmatch.fnmatch(x, '*{0}*'.format(target)) and target == _get_hold(x, full=False) ] if search_locks: if __opts__['test']: ret[target].update(result=None) ret[target]['comment'] = ('Package {0} is set to be unheld.' .format(target)) else: out = _call_yum(['versionlock', 'delete'] + search_locks) if out['retcode'] == 0: ret[target].update(result=True) ret[target]['comment'] = ('Package {0} is no longer held.' .format(target)) ret[target]['changes']['new'] = '' ret[target]['changes']['old'] = 'hold' else: ret[target]['comment'] = ('Package {0} was unable to be ' 'unheld.'.format(target)) else: ret[target].update(result=True) ret[target]['comment'] = ('Package {0} is not being held.' .format(target)) return ret
python
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 ''' .. versionadded:: 2014.7.0 Remove version locks .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` name The name of the package to be unheld Multiple Package Options: pkgs A list of packages to unhold. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.unhold <package name> salt '*' pkg.unhold pkgs='["foo", "bar"]' ''' _check_versionlock() if not name and not pkgs and not sources: raise SaltInvocationError( 'One of name, pkgs, or sources must be specified.' ) if pkgs and sources: raise SaltInvocationError( 'Only one of pkgs or sources can be specified.' ) targets = [] if pkgs: for pkg in salt.utils.data.repack_dictlist(pkgs): targets.append(pkg) elif sources: for source in sources: targets.append(next(iter(source))) else: targets.append(name) # Yum's versionlock plugin doesn't support passing just the package name # when removing a lock, so we need to get the full list and then use # fnmatch below to find the match. current_locks = list_holds(full=_yum() == 'yum') ret = {} for target in targets: if isinstance(target, dict): target = next(six.iterkeys(target)) ret[target] = {'name': target, 'changes': {}, 'result': False, 'comment': ''} if _yum() == 'dnf': search_locks = [x for x in current_locks if x == target] else: # To accommodate yum versionlock's lack of support for removing # locks using just the package name, we have to use fnmatch to do # glob matching on the target name, and then for each matching # expression double-check that the package name (obtained via # _get_hold()) matches the targeted package. search_locks = [ x for x in current_locks if fnmatch.fnmatch(x, '*{0}*'.format(target)) and target == _get_hold(x, full=False) ] if search_locks: if __opts__['test']: ret[target].update(result=None) ret[target]['comment'] = ('Package {0} is set to be unheld.' .format(target)) else: out = _call_yum(['versionlock', 'delete'] + search_locks) if out['retcode'] == 0: ret[target].update(result=True) ret[target]['comment'] = ('Package {0} is no longer held.' .format(target)) ret[target]['changes']['new'] = '' ret[target]['changes']['old'] = 'hold' else: ret[target]['comment'] = ('Package {0} was unable to be ' 'unheld.'.format(target)) else: ret[target].update(result=True) ret[target]['comment'] = ('Package {0} is not being held.' .format(target)) return ret
[ "def", "unhold", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "_check_versionlock", "(", ")", "if", "not", "name", "and", "not", "pkgs", "and", "not", "so...
.. versionadded:: 2014.7.0 Remove version locks .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` name The name of the package to be unheld Multiple Package Options: pkgs A list of packages to unhold. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.unhold <package name> salt '*' pkg.unhold pkgs='["foo", "bar"]'
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2167-L2269
train
saltstack/salt
salt/modules/yumpkg.py
list_holds
def list_holds(pattern=__HOLD_PATTERN, full=True): r''' .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 Function renamed from ``pkg.get_locked_pkgs`` to ``pkg.list_holds``. List information on locked packages .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` pattern : \w+(?:[.-][^-]+)* Regular expression used to match the package name full : True Show the full hold definition including version and epoch. Set to ``False`` to return just the name of the package(s) being held. CLI Example: .. code-block:: bash salt '*' pkg.list_holds salt '*' pkg.list_holds full=False ''' _check_versionlock() out = __salt__['cmd.run']([_yum(), 'versionlock', 'list'], python_shell=False) ret = [] for line in salt.utils.itertools.split(out, '\n'): match = _get_hold(line, pattern=pattern, full=full) if match is not None: ret.append(match) return ret
python
def list_holds(pattern=__HOLD_PATTERN, full=True): r''' .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 Function renamed from ``pkg.get_locked_pkgs`` to ``pkg.list_holds``. List information on locked packages .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` pattern : \w+(?:[.-][^-]+)* Regular expression used to match the package name full : True Show the full hold definition including version and epoch. Set to ``False`` to return just the name of the package(s) being held. CLI Example: .. code-block:: bash salt '*' pkg.list_holds salt '*' pkg.list_holds full=False ''' _check_versionlock() out = __salt__['cmd.run']([_yum(), 'versionlock', 'list'], python_shell=False) ret = [] for line in salt.utils.itertools.split(out, '\n'): match = _get_hold(line, pattern=pattern, full=full) if match is not None: ret.append(match) return ret
[ "def", "list_holds", "(", "pattern", "=", "__HOLD_PATTERN", ",", "full", "=", "True", ")", ":", "_check_versionlock", "(", ")", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "[", "_yum", "(", ")", ",", "'versionlock'", ",", "'list'", "]", ",", "p...
r''' .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 Function renamed from ``pkg.get_locked_pkgs`` to ``pkg.list_holds``. List information on locked packages .. note:: Requires the appropriate ``versionlock`` plugin package to be installed: - On RHEL 5: ``yum-versionlock`` - On RHEL 6 & 7: ``yum-plugin-versionlock`` - On Fedora: ``python-dnf-plugins-extras-versionlock`` pattern : \w+(?:[.-][^-]+)* Regular expression used to match the package name full : True Show the full hold definition including version and epoch. Set to ``False`` to return just the name of the package(s) being held. CLI Example: .. code-block:: bash salt '*' pkg.list_holds salt '*' pkg.list_holds full=False
[ "r", "..", "versionchanged", "::", "2016", ".", "3", ".", "0", "2015", ".", "8", ".", "4", "2015", ".", "5", ".", "10", "Function", "renamed", "from", "pkg", ".", "get_locked_pkgs", "to", "pkg", ".", "list_holds", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2272-L2310
train
saltstack/salt
salt/modules/yumpkg.py
group_list
def group_list(): ''' .. versionadded:: 2014.1.0 Lists all groups known by yum on this system CLI Example: .. code-block:: bash salt '*' pkg.group_list ''' ret = {'installed': [], 'available': [], 'installed environments': [], 'available environments': [], 'available languages': {}} section_map = { 'installed groups:': 'installed', 'available groups:': 'available', 'installed environment groups:': 'installed environments', 'available environment groups:': 'available environments', 'available language groups:': 'available languages', } out = __salt__['cmd.run_stdout']( [_yum(), 'grouplist', 'hidden'], output_loglevel='trace', python_shell=False ) key = None for line in salt.utils.itertools.split(out, '\n'): line_lc = line.lower() if line_lc == 'done': break section_lookup = section_map.get(line_lc) if section_lookup is not None and section_lookup != key: key = section_lookup continue # Ignore any administrative comments (plugin info, repo info, etc.) if key is None: continue line = line.strip() if key != 'available languages': ret[key].append(line) else: match = re.match(r'(.+) \[(.+)\]', line) if match: name, lang = match.groups() ret[key][line] = {'name': name, 'language': lang} return ret
python
def group_list(): ''' .. versionadded:: 2014.1.0 Lists all groups known by yum on this system CLI Example: .. code-block:: bash salt '*' pkg.group_list ''' ret = {'installed': [], 'available': [], 'installed environments': [], 'available environments': [], 'available languages': {}} section_map = { 'installed groups:': 'installed', 'available groups:': 'available', 'installed environment groups:': 'installed environments', 'available environment groups:': 'available environments', 'available language groups:': 'available languages', } out = __salt__['cmd.run_stdout']( [_yum(), 'grouplist', 'hidden'], output_loglevel='trace', python_shell=False ) key = None for line in salt.utils.itertools.split(out, '\n'): line_lc = line.lower() if line_lc == 'done': break section_lookup = section_map.get(line_lc) if section_lookup is not None and section_lookup != key: key = section_lookup continue # Ignore any administrative comments (plugin info, repo info, etc.) if key is None: continue line = line.strip() if key != 'available languages': ret[key].append(line) else: match = re.match(r'(.+) \[(.+)\]', line) if match: name, lang = match.groups() ret[key][line] = {'name': name, 'language': lang} return ret
[ "def", "group_list", "(", ")", ":", "ret", "=", "{", "'installed'", ":", "[", "]", ",", "'available'", ":", "[", "]", ",", "'installed environments'", ":", "[", "]", ",", "'available environments'", ":", "[", "]", ",", "'available languages'", ":", "{", ...
.. versionadded:: 2014.1.0 Lists all groups known by yum on this system CLI Example: .. code-block:: bash salt '*' pkg.group_list
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2341-L2395
train
saltstack/salt
salt/modules/yumpkg.py
group_info
def group_info(name, expand=False): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 The return data has changed. A new key ``type`` has been added to distinguish environment groups from package groups. Also, keys for the group name and group ID have been added. The ``mandatory packages``, ``optional packages``, and ``default packages`` keys have been renamed to ``mandatory``, ``optional``, and ``default`` for accuracy, as environment groups include other groups, and not packages. Finally, this function now properly identifies conditional packages. Lists packages belonging to a certain group name Name of the group to query expand : False If the specified group is an environment group, then the group will be expanded and the return data will include package names instead of group names. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' pkg.group_info 'Perl Support' ''' pkgtypes = ('mandatory', 'optional', 'default', 'conditional') ret = {} for pkgtype in pkgtypes: ret[pkgtype] = set() cmd = [_yum(), '--quiet', 'groupinfo', name] out = __salt__['cmd.run_stdout']( cmd, output_loglevel='trace', python_shell=False ) g_info = {} for line in salt.utils.itertools.split(out, '\n'): try: key, value = [x.strip() for x in line.split(':')] g_info[key.lower()] = value except ValueError: continue if 'environment group' in g_info: ret['type'] = 'environment group' elif 'group' in g_info: ret['type'] = 'package group' ret['group'] = g_info.get('environment group') or g_info.get('group') ret['id'] = g_info.get('environment-id') or g_info.get('group-id') if not ret['group'] and not ret['id']: raise CommandExecutionError('Group \'{0}\' not found'.format(name)) ret['description'] = g_info.get('description', '') pkgtypes_capturegroup = '(' + '|'.join(pkgtypes) + ')' for pkgtype in pkgtypes: target_found = False for line in salt.utils.itertools.split(out, '\n'): line = line.strip().lstrip(string.punctuation) match = re.match( pkgtypes_capturegroup + r' (?:groups|packages):\s*$', line.lower() ) if match: if target_found: # We've reached a new section, break from loop break else: if match.group(1) == pkgtype: # We've reached the targeted section target_found = True continue if target_found: if expand and ret['type'] == 'environment group': expanded = group_info(line, expand=True) # Don't shadow the pkgtype variable from the outer loop for p_type in pkgtypes: ret[p_type].update(set(expanded[p_type])) else: ret[pkgtype].add(line) for pkgtype in pkgtypes: ret[pkgtype] = sorted(ret[pkgtype]) return ret
python
def group_info(name, expand=False): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 The return data has changed. A new key ``type`` has been added to distinguish environment groups from package groups. Also, keys for the group name and group ID have been added. The ``mandatory packages``, ``optional packages``, and ``default packages`` keys have been renamed to ``mandatory``, ``optional``, and ``default`` for accuracy, as environment groups include other groups, and not packages. Finally, this function now properly identifies conditional packages. Lists packages belonging to a certain group name Name of the group to query expand : False If the specified group is an environment group, then the group will be expanded and the return data will include package names instead of group names. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' pkg.group_info 'Perl Support' ''' pkgtypes = ('mandatory', 'optional', 'default', 'conditional') ret = {} for pkgtype in pkgtypes: ret[pkgtype] = set() cmd = [_yum(), '--quiet', 'groupinfo', name] out = __salt__['cmd.run_stdout']( cmd, output_loglevel='trace', python_shell=False ) g_info = {} for line in salt.utils.itertools.split(out, '\n'): try: key, value = [x.strip() for x in line.split(':')] g_info[key.lower()] = value except ValueError: continue if 'environment group' in g_info: ret['type'] = 'environment group' elif 'group' in g_info: ret['type'] = 'package group' ret['group'] = g_info.get('environment group') or g_info.get('group') ret['id'] = g_info.get('environment-id') or g_info.get('group-id') if not ret['group'] and not ret['id']: raise CommandExecutionError('Group \'{0}\' not found'.format(name)) ret['description'] = g_info.get('description', '') pkgtypes_capturegroup = '(' + '|'.join(pkgtypes) + ')' for pkgtype in pkgtypes: target_found = False for line in salt.utils.itertools.split(out, '\n'): line = line.strip().lstrip(string.punctuation) match = re.match( pkgtypes_capturegroup + r' (?:groups|packages):\s*$', line.lower() ) if match: if target_found: # We've reached a new section, break from loop break else: if match.group(1) == pkgtype: # We've reached the targeted section target_found = True continue if target_found: if expand and ret['type'] == 'environment group': expanded = group_info(line, expand=True) # Don't shadow the pkgtype variable from the outer loop for p_type in pkgtypes: ret[p_type].update(set(expanded[p_type])) else: ret[pkgtype].add(line) for pkgtype in pkgtypes: ret[pkgtype] = sorted(ret[pkgtype]) return ret
[ "def", "group_info", "(", "name", ",", "expand", "=", "False", ")", ":", "pkgtypes", "=", "(", "'mandatory'", ",", "'optional'", ",", "'default'", ",", "'conditional'", ")", "ret", "=", "{", "}", "for", "pkgtype", "in", "pkgtypes", ":", "ret", "[", "pk...
.. versionadded:: 2014.1.0 .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 The return data has changed. A new key ``type`` has been added to distinguish environment groups from package groups. Also, keys for the group name and group ID have been added. The ``mandatory packages``, ``optional packages``, and ``default packages`` keys have been renamed to ``mandatory``, ``optional``, and ``default`` for accuracy, as environment groups include other groups, and not packages. Finally, this function now properly identifies conditional packages. Lists packages belonging to a certain group name Name of the group to query expand : False If the specified group is an environment group, then the group will be expanded and the return data will include package names instead of group names. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' pkg.group_info 'Perl Support'
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0", "..", "versionchanged", "::", "2016", ".", "3", ".", "0", "2015", ".", "8", ".", "4", "2015", ".", "5", ".", "10", "The", "return", "data", "has", "changed", ".", "A", "new", "key", "type", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2398-L2490
train
saltstack/salt
salt/modules/yumpkg.py
group_diff
def group_diff(name): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 Environment groups are now supported. The key names have been renamed, similar to the changes made in :py:func:`pkg.group_info <salt.modules.yumpkg.group_info>`. Lists which of a group's packages are installed and which are not installed CLI Example: .. code-block:: bash salt '*' pkg.group_diff 'Perl Support' ''' pkgtypes = ('mandatory', 'optional', 'default', 'conditional') ret = {} for pkgtype in pkgtypes: ret[pkgtype] = {'installed': [], 'not installed': []} pkgs = list_pkgs() group_pkgs = group_info(name, expand=True) for pkgtype in pkgtypes: for member in group_pkgs.get(pkgtype, []): if member in pkgs: ret[pkgtype]['installed'].append(member) else: ret[pkgtype]['not installed'].append(member) return ret
python
def group_diff(name): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 Environment groups are now supported. The key names have been renamed, similar to the changes made in :py:func:`pkg.group_info <salt.modules.yumpkg.group_info>`. Lists which of a group's packages are installed and which are not installed CLI Example: .. code-block:: bash salt '*' pkg.group_diff 'Perl Support' ''' pkgtypes = ('mandatory', 'optional', 'default', 'conditional') ret = {} for pkgtype in pkgtypes: ret[pkgtype] = {'installed': [], 'not installed': []} pkgs = list_pkgs() group_pkgs = group_info(name, expand=True) for pkgtype in pkgtypes: for member in group_pkgs.get(pkgtype, []): if member in pkgs: ret[pkgtype]['installed'].append(member) else: ret[pkgtype]['not installed'].append(member) return ret
[ "def", "group_diff", "(", "name", ")", ":", "pkgtypes", "=", "(", "'mandatory'", ",", "'optional'", ",", "'default'", ",", "'conditional'", ")", "ret", "=", "{", "}", "for", "pkgtype", "in", "pkgtypes", ":", "ret", "[", "pkgtype", "]", "=", "{", "'inst...
.. versionadded:: 2014.1.0 .. versionchanged:: 2016.3.0,2015.8.4,2015.5.10 Environment groups are now supported. The key names have been renamed, similar to the changes made in :py:func:`pkg.group_info <salt.modules.yumpkg.group_info>`. Lists which of a group's packages are installed and which are not installed CLI Example: .. code-block:: bash salt '*' pkg.group_diff 'Perl Support'
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0", "..", "versionchanged", "::", "2016", ".", "3", ".", "0", "2015", ".", "8", ".", "4", "2015", ".", "5", ".", "10", "Environment", "groups", "are", "now", "supported", ".", "The", "key", "names...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2493-L2523
train
saltstack/salt
salt/modules/yumpkg.py
group_install
def group_install(name, skip=(), include=(), **kwargs): ''' .. versionadded:: 2014.1.0 Install the passed package group(s). This is basically a wrapper around :py:func:`pkg.install <salt.modules.yumpkg.install>`, which performs package group resolution for the user. This function is currently considered experimental, and should be expected to undergo changes. name Package group to install. To install more than one group, either use a comma-separated list or pass the value as a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'Group 1' salt '*' pkg.group_install 'Group 1,Group 2' salt '*' pkg.group_install '["Group 1", "Group 2"]' skip Packages that would normally be installed by the package group ("default" packages), which should not be installed. Can be passed either as a comma-separated list or a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'My Group' skip='foo,bar' salt '*' pkg.group_install 'My Group' skip='["foo", "bar"]' include Packages which are included in a group, which would not normally be installed by a ``yum groupinstall`` ("optional" packages). Note that this will not enforce group membership; if you include packages which are not members of the specified groups, they will still be installed. Can be passed either as a comma-separated list or a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'My Group' include='foo,bar' salt '*' pkg.group_install 'My Group' include='["foo", "bar"]' .. note:: Because this is essentially a wrapper around pkg.install, any argument which can be passed to pkg.install may also be included here, and it will be passed along wholesale. ''' groups = name.split(',') if isinstance(name, six.string_types) else name if not groups: raise SaltInvocationError('no groups specified') elif not isinstance(groups, list): raise SaltInvocationError('\'groups\' must be a list') # pylint: disable=maybe-no-member if isinstance(skip, six.string_types): skip = skip.split(',') if not isinstance(skip, (list, tuple)): raise SaltInvocationError('\'skip\' must be a list') if isinstance(include, six.string_types): include = include.split(',') if not isinstance(include, (list, tuple)): raise SaltInvocationError('\'include\' must be a list') # pylint: enable=maybe-no-member targets = [] for group in groups: group_detail = group_info(group) targets.extend(group_detail.get('mandatory packages', [])) targets.extend( [pkg for pkg in group_detail.get('default packages', []) if pkg not in skip] ) if include: targets.extend(include) # Don't install packages that are already installed, install() isn't smart # enough to make this distinction. pkgs = [x for x in targets if x not in list_pkgs()] if not pkgs: return {} return install(pkgs=pkgs, **kwargs)
python
def group_install(name, skip=(), include=(), **kwargs): ''' .. versionadded:: 2014.1.0 Install the passed package group(s). This is basically a wrapper around :py:func:`pkg.install <salt.modules.yumpkg.install>`, which performs package group resolution for the user. This function is currently considered experimental, and should be expected to undergo changes. name Package group to install. To install more than one group, either use a comma-separated list or pass the value as a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'Group 1' salt '*' pkg.group_install 'Group 1,Group 2' salt '*' pkg.group_install '["Group 1", "Group 2"]' skip Packages that would normally be installed by the package group ("default" packages), which should not be installed. Can be passed either as a comma-separated list or a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'My Group' skip='foo,bar' salt '*' pkg.group_install 'My Group' skip='["foo", "bar"]' include Packages which are included in a group, which would not normally be installed by a ``yum groupinstall`` ("optional" packages). Note that this will not enforce group membership; if you include packages which are not members of the specified groups, they will still be installed. Can be passed either as a comma-separated list or a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'My Group' include='foo,bar' salt '*' pkg.group_install 'My Group' include='["foo", "bar"]' .. note:: Because this is essentially a wrapper around pkg.install, any argument which can be passed to pkg.install may also be included here, and it will be passed along wholesale. ''' groups = name.split(',') if isinstance(name, six.string_types) else name if not groups: raise SaltInvocationError('no groups specified') elif not isinstance(groups, list): raise SaltInvocationError('\'groups\' must be a list') # pylint: disable=maybe-no-member if isinstance(skip, six.string_types): skip = skip.split(',') if not isinstance(skip, (list, tuple)): raise SaltInvocationError('\'skip\' must be a list') if isinstance(include, six.string_types): include = include.split(',') if not isinstance(include, (list, tuple)): raise SaltInvocationError('\'include\' must be a list') # pylint: enable=maybe-no-member targets = [] for group in groups: group_detail = group_info(group) targets.extend(group_detail.get('mandatory packages', [])) targets.extend( [pkg for pkg in group_detail.get('default packages', []) if pkg not in skip] ) if include: targets.extend(include) # Don't install packages that are already installed, install() isn't smart # enough to make this distinction. pkgs = [x for x in targets if x not in list_pkgs()] if not pkgs: return {} return install(pkgs=pkgs, **kwargs)
[ "def", "group_install", "(", "name", ",", "skip", "=", "(", ")", ",", "include", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "groups", "=", "name", ".", "split", "(", "','", ")", "if", "isinstance", "(", "name", ",", "six", ".", "string_typ...
.. versionadded:: 2014.1.0 Install the passed package group(s). This is basically a wrapper around :py:func:`pkg.install <salt.modules.yumpkg.install>`, which performs package group resolution for the user. This function is currently considered experimental, and should be expected to undergo changes. name Package group to install. To install more than one group, either use a comma-separated list or pass the value as a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'Group 1' salt '*' pkg.group_install 'Group 1,Group 2' salt '*' pkg.group_install '["Group 1", "Group 2"]' skip Packages that would normally be installed by the package group ("default" packages), which should not be installed. Can be passed either as a comma-separated list or a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'My Group' skip='foo,bar' salt '*' pkg.group_install 'My Group' skip='["foo", "bar"]' include Packages which are included in a group, which would not normally be installed by a ``yum groupinstall`` ("optional" packages). Note that this will not enforce group membership; if you include packages which are not members of the specified groups, they will still be installed. Can be passed either as a comma-separated list or a python list. CLI Examples: .. code-block:: bash salt '*' pkg.group_install 'My Group' include='foo,bar' salt '*' pkg.group_install 'My Group' include='["foo", "bar"]' .. note:: Because this is essentially a wrapper around pkg.install, any argument which can be passed to pkg.install may also be included here, and it will be passed along wholesale.
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2526-L2617
train
saltstack/salt
salt/modules/yumpkg.py
list_repos
def list_repos(basedir=None, **kwargs): ''' Lists all repos in <basedir> (default: all dirs in `reposdir` yum option). CLI Example: .. code-block:: bash salt '*' pkg.list_repos salt '*' pkg.list_repos basedir=/path/to/dir salt '*' pkg.list_repos basedir=/path/to/dir,/path/to/another/dir ''' basedirs = _normalize_basedir(basedir) repos = {} log.debug('Searching for repos in %s', basedirs) for bdir in basedirs: if not os.path.exists(bdir): continue for repofile in os.listdir(bdir): repopath = '{0}/{1}'.format(bdir, repofile) if not repofile.endswith('.repo'): continue filerepos = _parse_repo_file(repopath)[1] for reponame in filerepos: repo = filerepos[reponame] repo['file'] = repopath repos[reponame] = repo return repos
python
def list_repos(basedir=None, **kwargs): ''' Lists all repos in <basedir> (default: all dirs in `reposdir` yum option). CLI Example: .. code-block:: bash salt '*' pkg.list_repos salt '*' pkg.list_repos basedir=/path/to/dir salt '*' pkg.list_repos basedir=/path/to/dir,/path/to/another/dir ''' basedirs = _normalize_basedir(basedir) repos = {} log.debug('Searching for repos in %s', basedirs) for bdir in basedirs: if not os.path.exists(bdir): continue for repofile in os.listdir(bdir): repopath = '{0}/{1}'.format(bdir, repofile) if not repofile.endswith('.repo'): continue filerepos = _parse_repo_file(repopath)[1] for reponame in filerepos: repo = filerepos[reponame] repo['file'] = repopath repos[reponame] = repo return repos
[ "def", "list_repos", "(", "basedir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "basedirs", "=", "_normalize_basedir", "(", "basedir", ")", "repos", "=", "{", "}", "log", ".", "debug", "(", "'Searching for repos in %s'", ",", "basedirs", ")", "for", ...
Lists all repos in <basedir> (default: all dirs in `reposdir` yum option). CLI Example: .. code-block:: bash salt '*' pkg.list_repos salt '*' pkg.list_repos basedir=/path/to/dir salt '*' pkg.list_repos basedir=/path/to/dir,/path/to/another/dir
[ "Lists", "all", "repos", "in", "<basedir", ">", "(", "default", ":", "all", "dirs", "in", "reposdir", "yum", "option", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2623-L2651
train
saltstack/salt
salt/modules/yumpkg.py
get_repo
def get_repo(name, basedir=None, **kwargs): # pylint: disable=W0613 ''' Display a repo from <basedir> (default basedir: all dirs in ``reposdir`` yum option). CLI Examples: .. code-block:: bash salt '*' pkg.get_repo myrepo salt '*' pkg.get_repo myrepo basedir=/path/to/dir salt '*' pkg.get_repo myrepo basedir=/path/to/dir,/path/to/another/dir ''' repos = list_repos(basedir) # Find out what file the repo lives in repofile = '' for repo in repos: if repo == name: repofile = repos[repo]['file'] if repofile: # Return just one repo filerepos = _parse_repo_file(repofile)[1] return filerepos[name] return {}
python
def get_repo(name, basedir=None, **kwargs): # pylint: disable=W0613 ''' Display a repo from <basedir> (default basedir: all dirs in ``reposdir`` yum option). CLI Examples: .. code-block:: bash salt '*' pkg.get_repo myrepo salt '*' pkg.get_repo myrepo basedir=/path/to/dir salt '*' pkg.get_repo myrepo basedir=/path/to/dir,/path/to/another/dir ''' repos = list_repos(basedir) # Find out what file the repo lives in repofile = '' for repo in repos: if repo == name: repofile = repos[repo]['file'] if repofile: # Return just one repo filerepos = _parse_repo_file(repofile)[1] return filerepos[name] return {}
[ "def", "get_repo", "(", "name", ",", "basedir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "repos", "=", "list_repos", "(", "basedir", ")", "# Find out what file the repo lives in", "repofile", "=", "''", "for", "repo", "in", "r...
Display a repo from <basedir> (default basedir: all dirs in ``reposdir`` yum option). CLI Examples: .. code-block:: bash salt '*' pkg.get_repo myrepo salt '*' pkg.get_repo myrepo basedir=/path/to/dir salt '*' pkg.get_repo myrepo basedir=/path/to/dir,/path/to/another/dir
[ "Display", "a", "repo", "from", "<basedir", ">", "(", "default", "basedir", ":", "all", "dirs", "in", "reposdir", "yum", "option", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2654-L2679
train
saltstack/salt
salt/modules/yumpkg.py
del_repo
def del_repo(repo, basedir=None, **kwargs): # pylint: disable=W0613 ''' Delete a repo from <basedir> (default basedir: all dirs in `reposdir` yum option). If the .repo file in which the repo exists does not contain any other repo configuration, the file itself will be deleted. CLI Examples: .. code-block:: bash salt '*' pkg.del_repo myrepo salt '*' pkg.del_repo myrepo basedir=/path/to/dir salt '*' pkg.del_repo myrepo basedir=/path/to/dir,/path/to/another/dir ''' # this is so we know which dirs are searched for our error messages below basedirs = _normalize_basedir(basedir) repos = list_repos(basedirs) if repo not in repos: return 'Error: the {0} repo does not exist in {1}'.format( repo, basedirs) # Find out what file the repo lives in repofile = '' for arepo in repos: if arepo == repo: repofile = repos[arepo]['file'] # See if the repo is the only one in the file onlyrepo = True for arepo in six.iterkeys(repos): if arepo == repo: continue if repos[arepo]['file'] == repofile: onlyrepo = False # If this is the only repo in the file, delete the file itself if onlyrepo: os.remove(repofile) return 'File {0} containing repo {1} has been removed'.format( repofile, repo) # There must be other repos in this file, write the file with them header, filerepos = _parse_repo_file(repofile) content = header for stanza in six.iterkeys(filerepos): if stanza == repo: continue comments = '' if 'comments' in six.iterkeys(filerepos[stanza]): comments = salt.utils.pkg.rpm.combine_comments( filerepos[stanza]['comments']) del filerepos[stanza]['comments'] content += '\n[{0}]'.format(stanza) for line in filerepos[stanza]: content += '\n{0}={1}'.format(line, filerepos[stanza][line]) content += '\n{0}\n'.format(comments) with salt.utils.files.fopen(repofile, 'w') as fileout: fileout.write(salt.utils.stringutils.to_str(content)) return 'Repo {0} has been removed from {1}'.format(repo, repofile)
python
def del_repo(repo, basedir=None, **kwargs): # pylint: disable=W0613 ''' Delete a repo from <basedir> (default basedir: all dirs in `reposdir` yum option). If the .repo file in which the repo exists does not contain any other repo configuration, the file itself will be deleted. CLI Examples: .. code-block:: bash salt '*' pkg.del_repo myrepo salt '*' pkg.del_repo myrepo basedir=/path/to/dir salt '*' pkg.del_repo myrepo basedir=/path/to/dir,/path/to/another/dir ''' # this is so we know which dirs are searched for our error messages below basedirs = _normalize_basedir(basedir) repos = list_repos(basedirs) if repo not in repos: return 'Error: the {0} repo does not exist in {1}'.format( repo, basedirs) # Find out what file the repo lives in repofile = '' for arepo in repos: if arepo == repo: repofile = repos[arepo]['file'] # See if the repo is the only one in the file onlyrepo = True for arepo in six.iterkeys(repos): if arepo == repo: continue if repos[arepo]['file'] == repofile: onlyrepo = False # If this is the only repo in the file, delete the file itself if onlyrepo: os.remove(repofile) return 'File {0} containing repo {1} has been removed'.format( repofile, repo) # There must be other repos in this file, write the file with them header, filerepos = _parse_repo_file(repofile) content = header for stanza in six.iterkeys(filerepos): if stanza == repo: continue comments = '' if 'comments' in six.iterkeys(filerepos[stanza]): comments = salt.utils.pkg.rpm.combine_comments( filerepos[stanza]['comments']) del filerepos[stanza]['comments'] content += '\n[{0}]'.format(stanza) for line in filerepos[stanza]: content += '\n{0}={1}'.format(line, filerepos[stanza][line]) content += '\n{0}\n'.format(comments) with salt.utils.files.fopen(repofile, 'w') as fileout: fileout.write(salt.utils.stringutils.to_str(content)) return 'Repo {0} has been removed from {1}'.format(repo, repofile)
[ "def", "del_repo", "(", "repo", ",", "basedir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "# this is so we know which dirs are searched for our error messages below", "basedirs", "=", "_normalize_basedir", "(", "basedir", ")", "repos", "...
Delete a repo from <basedir> (default basedir: all dirs in `reposdir` yum option). If the .repo file in which the repo exists does not contain any other repo configuration, the file itself will be deleted. CLI Examples: .. code-block:: bash salt '*' pkg.del_repo myrepo salt '*' pkg.del_repo myrepo basedir=/path/to/dir salt '*' pkg.del_repo myrepo basedir=/path/to/dir,/path/to/another/dir
[ "Delete", "a", "repo", "from", "<basedir", ">", "(", "default", "basedir", ":", "all", "dirs", "in", "reposdir", "yum", "option", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2682-L2745
train
saltstack/salt
salt/modules/yumpkg.py
mod_repo
def mod_repo(repo, basedir=None, **kwargs): ''' Modify one or more values for a repo. If the repo does not exist, it will be created, so long as the following values are specified: repo name by which the yum refers to the repo name a human-readable name for the repo baseurl the URL for yum to reference mirrorlist the URL for yum to reference key_url the URL to gather the repo key from (salt:// or any other scheme supported by cp.cache_file) Key/Value pairs may also be removed from a repo's configuration by setting a key to a blank value. Bear in mind that a name cannot be deleted, and a baseurl can only be deleted if a mirrorlist is specified (or vice versa). CLI Examples: .. code-block:: bash salt '*' pkg.mod_repo reponame enabled=1 gpgcheck=1 salt '*' pkg.mod_repo reponame basedir=/path/to/dir enabled=1 salt '*' pkg.mod_repo reponame baseurl= mirrorlist=http://host.com/ ''' # Filter out '__pub' arguments, as well as saltenv repo_opts = dict( (x, kwargs[x]) for x in kwargs if not x.startswith('__') and x not in ('saltenv',) ) if all(x in repo_opts for x in ('mirrorlist', 'baseurl')): raise SaltInvocationError( 'Only one of \'mirrorlist\' and \'baseurl\' can be specified' ) # Build a list of keys to be deleted todelete = [] # list() of keys because the dict could be shrinking in the for loop. for key in list(repo_opts): if repo_opts[key] != 0 and not repo_opts[key]: del repo_opts[key] todelete.append(key) # Add baseurl or mirrorlist to the 'todelete' list if the other was # specified in the repo_opts if 'mirrorlist' in repo_opts: todelete.append('baseurl') elif 'baseurl' in repo_opts: todelete.append('mirrorlist') # Fail if the user tried to delete the name if 'name' in todelete: raise SaltInvocationError('The repo name cannot be deleted') # Give the user the ability to change the basedir repos = {} basedirs = _normalize_basedir(basedir) repos = list_repos(basedirs) repofile = '' header = '' filerepos = {} if repo not in repos: # If the repo doesn't exist, create it in a new file in the first # repo directory that exists newdir = None for d in basedirs: if os.path.exists(d): newdir = d break if not newdir: raise SaltInvocationError( 'The repo does not exist and needs to be created, but none ' 'of the following basedir directories exist: {0}'.format(basedirs) ) repofile = '{0}/{1}.repo'.format(newdir, repo) if 'name' not in repo_opts: raise SaltInvocationError( 'The repo does not exist and needs to be created, but a name ' 'was not given' ) if 'baseurl' not in repo_opts and 'mirrorlist' not in repo_opts: raise SaltInvocationError( 'The repo does not exist and needs to be created, but either ' 'a baseurl or a mirrorlist needs to be given' ) filerepos[repo] = {} else: # The repo does exist, open its file repofile = repos[repo]['file'] header, filerepos = _parse_repo_file(repofile) # Error out if they tried to delete baseurl or mirrorlist improperly if 'baseurl' in todelete: if 'mirrorlist' not in repo_opts and 'mirrorlist' \ not in filerepos[repo]: raise SaltInvocationError( 'Cannot delete baseurl without specifying mirrorlist' ) if 'mirrorlist' in todelete: if 'baseurl' not in repo_opts and 'baseurl' \ not in filerepos[repo]: raise SaltInvocationError( 'Cannot delete mirrorlist without specifying baseurl' ) # Import repository gpg key if 'key_url' in repo_opts: key_url = kwargs['key_url'] fn_ = __salt__['cp.cache_file'](key_url, saltenv=(kwargs['saltenv'] if 'saltenv' in kwargs else 'base')) if not fn_: raise CommandExecutionError( 'Error: Unable to copy key from URL {0} for repository {1}'.format(key_url, repo_opts['name']) ) cmd = ['rpm', '--import', fn_] out = __salt__['cmd.retcode'](cmd, python_shell=False, **kwargs) if out != salt.defaults.exitcodes.EX_OK: raise CommandExecutionError( 'Error: Unable to import key from URL {0} for repository {1}'.format(key_url, repo_opts['name']) ) del repo_opts['key_url'] # Delete anything in the todelete list for key in todelete: if key in six.iterkeys(filerepos[repo].copy()): del filerepos[repo][key] _bool_to_str = lambda x: '1' if x else '0' # Old file or new, write out the repos(s) filerepos[repo].update(repo_opts) content = header for stanza in six.iterkeys(filerepos): comments = salt.utils.pkg.rpm.combine_comments( filerepos[stanza].pop('comments', []) ) content += '[{0}]\n'.format(stanza) for line in six.iterkeys(filerepos[stanza]): content += '{0}={1}\n'.format( line, filerepos[stanza][line] if not isinstance(filerepos[stanza][line], bool) else _bool_to_str(filerepos[stanza][line]) ) content += comments + '\n' with salt.utils.files.fopen(repofile, 'w') as fileout: fileout.write(salt.utils.stringutils.to_str(content)) return {repofile: filerepos}
python
def mod_repo(repo, basedir=None, **kwargs): ''' Modify one or more values for a repo. If the repo does not exist, it will be created, so long as the following values are specified: repo name by which the yum refers to the repo name a human-readable name for the repo baseurl the URL for yum to reference mirrorlist the URL for yum to reference key_url the URL to gather the repo key from (salt:// or any other scheme supported by cp.cache_file) Key/Value pairs may also be removed from a repo's configuration by setting a key to a blank value. Bear in mind that a name cannot be deleted, and a baseurl can only be deleted if a mirrorlist is specified (or vice versa). CLI Examples: .. code-block:: bash salt '*' pkg.mod_repo reponame enabled=1 gpgcheck=1 salt '*' pkg.mod_repo reponame basedir=/path/to/dir enabled=1 salt '*' pkg.mod_repo reponame baseurl= mirrorlist=http://host.com/ ''' # Filter out '__pub' arguments, as well as saltenv repo_opts = dict( (x, kwargs[x]) for x in kwargs if not x.startswith('__') and x not in ('saltenv',) ) if all(x in repo_opts for x in ('mirrorlist', 'baseurl')): raise SaltInvocationError( 'Only one of \'mirrorlist\' and \'baseurl\' can be specified' ) # Build a list of keys to be deleted todelete = [] # list() of keys because the dict could be shrinking in the for loop. for key in list(repo_opts): if repo_opts[key] != 0 and not repo_opts[key]: del repo_opts[key] todelete.append(key) # Add baseurl or mirrorlist to the 'todelete' list if the other was # specified in the repo_opts if 'mirrorlist' in repo_opts: todelete.append('baseurl') elif 'baseurl' in repo_opts: todelete.append('mirrorlist') # Fail if the user tried to delete the name if 'name' in todelete: raise SaltInvocationError('The repo name cannot be deleted') # Give the user the ability to change the basedir repos = {} basedirs = _normalize_basedir(basedir) repos = list_repos(basedirs) repofile = '' header = '' filerepos = {} if repo not in repos: # If the repo doesn't exist, create it in a new file in the first # repo directory that exists newdir = None for d in basedirs: if os.path.exists(d): newdir = d break if not newdir: raise SaltInvocationError( 'The repo does not exist and needs to be created, but none ' 'of the following basedir directories exist: {0}'.format(basedirs) ) repofile = '{0}/{1}.repo'.format(newdir, repo) if 'name' not in repo_opts: raise SaltInvocationError( 'The repo does not exist and needs to be created, but a name ' 'was not given' ) if 'baseurl' not in repo_opts and 'mirrorlist' not in repo_opts: raise SaltInvocationError( 'The repo does not exist and needs to be created, but either ' 'a baseurl or a mirrorlist needs to be given' ) filerepos[repo] = {} else: # The repo does exist, open its file repofile = repos[repo]['file'] header, filerepos = _parse_repo_file(repofile) # Error out if they tried to delete baseurl or mirrorlist improperly if 'baseurl' in todelete: if 'mirrorlist' not in repo_opts and 'mirrorlist' \ not in filerepos[repo]: raise SaltInvocationError( 'Cannot delete baseurl without specifying mirrorlist' ) if 'mirrorlist' in todelete: if 'baseurl' not in repo_opts and 'baseurl' \ not in filerepos[repo]: raise SaltInvocationError( 'Cannot delete mirrorlist without specifying baseurl' ) # Import repository gpg key if 'key_url' in repo_opts: key_url = kwargs['key_url'] fn_ = __salt__['cp.cache_file'](key_url, saltenv=(kwargs['saltenv'] if 'saltenv' in kwargs else 'base')) if not fn_: raise CommandExecutionError( 'Error: Unable to copy key from URL {0} for repository {1}'.format(key_url, repo_opts['name']) ) cmd = ['rpm', '--import', fn_] out = __salt__['cmd.retcode'](cmd, python_shell=False, **kwargs) if out != salt.defaults.exitcodes.EX_OK: raise CommandExecutionError( 'Error: Unable to import key from URL {0} for repository {1}'.format(key_url, repo_opts['name']) ) del repo_opts['key_url'] # Delete anything in the todelete list for key in todelete: if key in six.iterkeys(filerepos[repo].copy()): del filerepos[repo][key] _bool_to_str = lambda x: '1' if x else '0' # Old file or new, write out the repos(s) filerepos[repo].update(repo_opts) content = header for stanza in six.iterkeys(filerepos): comments = salt.utils.pkg.rpm.combine_comments( filerepos[stanza].pop('comments', []) ) content += '[{0}]\n'.format(stanza) for line in six.iterkeys(filerepos[stanza]): content += '{0}={1}\n'.format( line, filerepos[stanza][line] if not isinstance(filerepos[stanza][line], bool) else _bool_to_str(filerepos[stanza][line]) ) content += comments + '\n' with salt.utils.files.fopen(repofile, 'w') as fileout: fileout.write(salt.utils.stringutils.to_str(content)) return {repofile: filerepos}
[ "def", "mod_repo", "(", "repo", ",", "basedir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Filter out '__pub' arguments, as well as saltenv", "repo_opts", "=", "dict", "(", "(", "x", ",", "kwargs", "[", "x", "]", ")", "for", "x", "in", "kwargs", ...
Modify one or more values for a repo. If the repo does not exist, it will be created, so long as the following values are specified: repo name by which the yum refers to the repo name a human-readable name for the repo baseurl the URL for yum to reference mirrorlist the URL for yum to reference key_url the URL to gather the repo key from (salt:// or any other scheme supported by cp.cache_file) Key/Value pairs may also be removed from a repo's configuration by setting a key to a blank value. Bear in mind that a name cannot be deleted, and a baseurl can only be deleted if a mirrorlist is specified (or vice versa). CLI Examples: .. code-block:: bash salt '*' pkg.mod_repo reponame enabled=1 gpgcheck=1 salt '*' pkg.mod_repo reponame basedir=/path/to/dir enabled=1 salt '*' pkg.mod_repo reponame baseurl= mirrorlist=http://host.com/
[ "Modify", "one", "or", "more", "values", "for", "a", "repo", ".", "If", "the", "repo", "does", "not", "exist", "it", "will", "be", "created", "so", "long", "as", "the", "following", "values", "are", "specified", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2748-L2903
train
saltstack/salt
salt/modules/yumpkg.py
_parse_repo_file
def _parse_repo_file(filename): ''' Turn a single repo file into a dict ''' parsed = configparser.ConfigParser() config = {} try: parsed.read(filename) except configparser.MissingSectionHeaderError as err: log.error( 'Failed to parse file %s, error: %s', filename, err.message ) return ('', {}) for section in parsed._sections: section_dict = dict(parsed._sections[section]) section_dict.pop('__name__', None) config[section] = section_dict # Try to extract header comments, as well as comments for each repo. Read # from the beginning of the file and assume any leading comments are # header comments. Continue to read each section header and then find the # comments for each repo. headers = '' section = None with salt.utils.files.fopen(filename, 'r') as repofile: for line in repofile: line = salt.utils.stringutils.to_unicode(line) line = line.strip() if line.startswith('#'): if section is None: headers += line + '\n' else: try: comments = config[section].setdefault('comments', []) comments.append(line[1:].lstrip()) except KeyError: log.debug( 'Found comment in %s which does not appear to ' 'belong to any repo section: %s', filename, line ) elif line.startswith('[') and line.endswith(']'): section = line[1:-1] return (headers, salt.utils.data.decode(config))
python
def _parse_repo_file(filename): ''' Turn a single repo file into a dict ''' parsed = configparser.ConfigParser() config = {} try: parsed.read(filename) except configparser.MissingSectionHeaderError as err: log.error( 'Failed to parse file %s, error: %s', filename, err.message ) return ('', {}) for section in parsed._sections: section_dict = dict(parsed._sections[section]) section_dict.pop('__name__', None) config[section] = section_dict # Try to extract header comments, as well as comments for each repo. Read # from the beginning of the file and assume any leading comments are # header comments. Continue to read each section header and then find the # comments for each repo. headers = '' section = None with salt.utils.files.fopen(filename, 'r') as repofile: for line in repofile: line = salt.utils.stringutils.to_unicode(line) line = line.strip() if line.startswith('#'): if section is None: headers += line + '\n' else: try: comments = config[section].setdefault('comments', []) comments.append(line[1:].lstrip()) except KeyError: log.debug( 'Found comment in %s which does not appear to ' 'belong to any repo section: %s', filename, line ) elif line.startswith('[') and line.endswith(']'): section = line[1:-1] return (headers, salt.utils.data.decode(config))
[ "def", "_parse_repo_file", "(", "filename", ")", ":", "parsed", "=", "configparser", ".", "ConfigParser", "(", ")", "config", "=", "{", "}", "try", ":", "parsed", ".", "read", "(", "filename", ")", "except", "configparser", ".", "MissingSectionHeaderError", ...
Turn a single repo file into a dict
[ "Turn", "a", "single", "repo", "file", "into", "a", "dict" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2906-L2952
train
saltstack/salt
salt/modules/yumpkg.py
owner
def owner(*paths, **kwargs): ''' .. versionadded:: 2014.7.0 Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.yumpkg.version>`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Examples: .. code-block:: bash salt '*' pkg.owner /usr/bin/apachectl salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf ''' if not paths: return '' ret = {} cmd_prefix = ['rpm', '-qf', '--queryformat', '%{name}'] for path in paths: ret[path] = __salt__['cmd.run_stdout']( cmd_prefix + [path], output_loglevel='trace', python_shell=False ) if 'not owned' in ret[path].lower(): ret[path] = '' if len(ret) == 1: return next(six.itervalues(ret)) return ret
python
def owner(*paths, **kwargs): ''' .. versionadded:: 2014.7.0 Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.yumpkg.version>`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Examples: .. code-block:: bash salt '*' pkg.owner /usr/bin/apachectl salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf ''' if not paths: return '' ret = {} cmd_prefix = ['rpm', '-qf', '--queryformat', '%{name}'] for path in paths: ret[path] = __salt__['cmd.run_stdout']( cmd_prefix + [path], output_loglevel='trace', python_shell=False ) if 'not owned' in ret[path].lower(): ret[path] = '' if len(ret) == 1: return next(six.itervalues(ret)) return ret
[ "def", "owner", "(", "*", "paths", ",", "*", "*", "kwargs", ")", ":", "if", "not", "paths", ":", "return", "''", "ret", "=", "{", "}", "cmd_prefix", "=", "[", "'rpm'", ",", "'-qf'", ",", "'--queryformat'", ",", "'%{name}'", "]", "for", "path", "in"...
.. versionadded:: 2014.7.0 Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.yumpkg.version>`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Examples: .. code-block:: bash salt '*' pkg.owner /usr/bin/apachectl salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L2993-L3026
train
saltstack/salt
salt/modules/yumpkg.py
download
def download(*packages, **kwargs): ''' .. versionadded:: 2015.5.0 Download packages to the local disk. Requires ``yumdownloader`` from ``yum-utils`` package. .. note:: ``yum-utils`` will already be installed on the minion if the package was installed from the Fedora / EPEL repositories. CLI example: .. code-block:: bash salt '*' pkg.download httpd salt '*' pkg.download httpd postfix ''' if not packages: raise SaltInvocationError('No packages were specified') CACHE_DIR = '/var/cache/yum/packages' if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) cached_pkgs = os.listdir(CACHE_DIR) to_purge = [] for pkg in packages: to_purge.extend([os.path.join(CACHE_DIR, x) for x in cached_pkgs if x.startswith('{0}-'.format(pkg))]) for purge_target in set(to_purge): log.debug('Removing cached package %s', purge_target) try: os.unlink(purge_target) except OSError as exc: log.error('Unable to remove %s: %s', purge_target, exc) cmd = ['yumdownloader', '-q', '--destdir={0}'.format(CACHE_DIR)] cmd.extend(packages) __salt__['cmd.run']( cmd, output_loglevel='trace', python_shell=False ) ret = {} for dld_result in os.listdir(CACHE_DIR): if not dld_result.endswith('.rpm'): continue pkg_name = None pkg_file = None for query_pkg in packages: if dld_result.startswith('{0}-'.format(query_pkg)): pkg_name = query_pkg pkg_file = dld_result break if pkg_file is not None: ret[pkg_name] = os.path.join(CACHE_DIR, pkg_file) if not ret: raise CommandExecutionError( 'Unable to download any of the following packages: {0}' .format(', '.join(packages)) ) failed = [x for x in packages if x not in ret] if failed: ret['_error'] = ('The following package(s) failed to download: {0}' .format(', '.join(failed))) return ret
python
def download(*packages, **kwargs): ''' .. versionadded:: 2015.5.0 Download packages to the local disk. Requires ``yumdownloader`` from ``yum-utils`` package. .. note:: ``yum-utils`` will already be installed on the minion if the package was installed from the Fedora / EPEL repositories. CLI example: .. code-block:: bash salt '*' pkg.download httpd salt '*' pkg.download httpd postfix ''' if not packages: raise SaltInvocationError('No packages were specified') CACHE_DIR = '/var/cache/yum/packages' if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) cached_pkgs = os.listdir(CACHE_DIR) to_purge = [] for pkg in packages: to_purge.extend([os.path.join(CACHE_DIR, x) for x in cached_pkgs if x.startswith('{0}-'.format(pkg))]) for purge_target in set(to_purge): log.debug('Removing cached package %s', purge_target) try: os.unlink(purge_target) except OSError as exc: log.error('Unable to remove %s: %s', purge_target, exc) cmd = ['yumdownloader', '-q', '--destdir={0}'.format(CACHE_DIR)] cmd.extend(packages) __salt__['cmd.run']( cmd, output_loglevel='trace', python_shell=False ) ret = {} for dld_result in os.listdir(CACHE_DIR): if not dld_result.endswith('.rpm'): continue pkg_name = None pkg_file = None for query_pkg in packages: if dld_result.startswith('{0}-'.format(query_pkg)): pkg_name = query_pkg pkg_file = dld_result break if pkg_file is not None: ret[pkg_name] = os.path.join(CACHE_DIR, pkg_file) if not ret: raise CommandExecutionError( 'Unable to download any of the following packages: {0}' .format(', '.join(packages)) ) failed = [x for x in packages if x not in ret] if failed: ret['_error'] = ('The following package(s) failed to download: {0}' .format(', '.join(failed))) return ret
[ "def", "download", "(", "*", "packages", ",", "*", "*", "kwargs", ")", ":", "if", "not", "packages", ":", "raise", "SaltInvocationError", "(", "'No packages were specified'", ")", "CACHE_DIR", "=", "'/var/cache/yum/packages'", "if", "not", "os", ".", "path", "...
.. versionadded:: 2015.5.0 Download packages to the local disk. Requires ``yumdownloader`` from ``yum-utils`` package. .. note:: ``yum-utils`` will already be installed on the minion if the package was installed from the Fedora / EPEL repositories. CLI example: .. code-block:: bash salt '*' pkg.download httpd salt '*' pkg.download httpd postfix
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L3081-L3150
train
saltstack/salt
salt/modules/yumpkg.py
diff
def diff(*paths, **kwargs): ''' Return a formatted diff between current files and original in a package. NOTE: this function includes all files (configuration and not), but does not work on binary content. :param path: Full path to the installed file :return: Difference string or raises and exception if examined file is binary. CLI example: .. code-block:: bash salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers ''' ret = {} pkg_to_paths = {} for pth in paths: pth_pkg = __salt__['lowpkg.owner'](pth) if not pth_pkg: ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A' else: if pkg_to_paths.get(pth_pkg) is None: pkg_to_paths[pth_pkg] = [] pkg_to_paths[pth_pkg].append(pth) if pkg_to_paths: local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys()) for pkg, files in pkg_to_paths.items(): for path in files: ret[path] = __salt__['lowpkg.diff']( local_pkgs[pkg]['path'], path) or 'Unchanged' return ret
python
def diff(*paths, **kwargs): ''' Return a formatted diff between current files and original in a package. NOTE: this function includes all files (configuration and not), but does not work on binary content. :param path: Full path to the installed file :return: Difference string or raises and exception if examined file is binary. CLI example: .. code-block:: bash salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers ''' ret = {} pkg_to_paths = {} for pth in paths: pth_pkg = __salt__['lowpkg.owner'](pth) if not pth_pkg: ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A' else: if pkg_to_paths.get(pth_pkg) is None: pkg_to_paths[pth_pkg] = [] pkg_to_paths[pth_pkg].append(pth) if pkg_to_paths: local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys()) for pkg, files in pkg_to_paths.items(): for path in files: ret[path] = __salt__['lowpkg.diff']( local_pkgs[pkg]['path'], path) or 'Unchanged' return ret
[ "def", "diff", "(", "*", "paths", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "pkg_to_paths", "=", "{", "}", "for", "pth", "in", "paths", ":", "pth_pkg", "=", "__salt__", "[", "'lowpkg.owner'", "]", "(", "pth", ")", "if", "not", "pth...
Return a formatted diff between current files and original in a package. NOTE: this function includes all files (configuration and not), but does not work on binary content. :param path: Full path to the installed file :return: Difference string or raises and exception if examined file is binary. CLI example: .. code-block:: bash salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
[ "Return", "a", "formatted", "diff", "between", "current", "files", "and", "original", "in", "a", "package", ".", "NOTE", ":", "this", "function", "includes", "all", "files", "(", "configuration", "and", "not", ")", "but", "does", "not", "work", "on", "bina...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L3153-L3187
train
saltstack/salt
salt/modules/yumpkg.py
_get_patches
def _get_patches(installed_only=False): ''' List all known patches in repos. ''' patches = {} cmd = [_yum(), '--quiet', 'updateinfo', 'list', 'all'] ret = __salt__['cmd.run_stdout']( cmd, python_shell=False ) for line in salt.utils.itertools.split(ret, os.linesep): inst, advisory_id, sev, pkg = re.match(r'([i|\s]) ([^\s]+) +([^\s]+) +([^\s]+)', line).groups() if inst != 'i' and installed_only: continue patches[advisory_id] = { 'installed': True if inst == 'i' else False, 'summary': pkg } return patches
python
def _get_patches(installed_only=False): ''' List all known patches in repos. ''' patches = {} cmd = [_yum(), '--quiet', 'updateinfo', 'list', 'all'] ret = __salt__['cmd.run_stdout']( cmd, python_shell=False ) for line in salt.utils.itertools.split(ret, os.linesep): inst, advisory_id, sev, pkg = re.match(r'([i|\s]) ([^\s]+) +([^\s]+) +([^\s]+)', line).groups() if inst != 'i' and installed_only: continue patches[advisory_id] = { 'installed': True if inst == 'i' else False, 'summary': pkg } return patches
[ "def", "_get_patches", "(", "installed_only", "=", "False", ")", ":", "patches", "=", "{", "}", "cmd", "=", "[", "_yum", "(", ")", ",", "'--quiet'", ",", "'updateinfo'", ",", "'list'", ",", "'all'", "]", "ret", "=", "__salt__", "[", "'cmd.run_stdout'", ...
List all known patches in repos.
[ "List", "all", "known", "patches", "in", "repos", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L3190-L3210
train
saltstack/salt
salt/modules/yumpkg.py
complete_transaction
def complete_transaction(cleanup_only=False, recursive=False, max_attempts=3): ''' .. versionadded:: Fluorine Execute ``yum-complete-transaction``, which is provided by the ``yum-utils`` package. cleanup_only Specify if the ``--cleanup-only`` option should be supplied. recursive Specify if ``yum-complete-transaction`` should be called recursively (it only completes one transaction at a time). max_attempts If ``recursive`` is ``True``, the maximum times ``yum-complete-transaction`` should be called. .. note:: Recursive calls will stop once ``No unfinished transactions left.`` is in the returned output. .. note:: ``yum-utils`` will already be installed on the minion if the package was installed from the Fedora / EPEL repositories. CLI example: .. code-block:: bash salt '*' pkg.complete_transaction salt '*' pkg.complete_transaction cleanup_only=True salt '*' pkg.complete_transaction recursive=True max_attempts=5 ''' return _complete_transaction(cleanup_only, recursive, max_attempts, 1, [])
python
def complete_transaction(cleanup_only=False, recursive=False, max_attempts=3): ''' .. versionadded:: Fluorine Execute ``yum-complete-transaction``, which is provided by the ``yum-utils`` package. cleanup_only Specify if the ``--cleanup-only`` option should be supplied. recursive Specify if ``yum-complete-transaction`` should be called recursively (it only completes one transaction at a time). max_attempts If ``recursive`` is ``True``, the maximum times ``yum-complete-transaction`` should be called. .. note:: Recursive calls will stop once ``No unfinished transactions left.`` is in the returned output. .. note:: ``yum-utils`` will already be installed on the minion if the package was installed from the Fedora / EPEL repositories. CLI example: .. code-block:: bash salt '*' pkg.complete_transaction salt '*' pkg.complete_transaction cleanup_only=True salt '*' pkg.complete_transaction recursive=True max_attempts=5 ''' return _complete_transaction(cleanup_only, recursive, max_attempts, 1, [])
[ "def", "complete_transaction", "(", "cleanup_only", "=", "False", ",", "recursive", "=", "False", ",", "max_attempts", "=", "3", ")", ":", "return", "_complete_transaction", "(", "cleanup_only", ",", "recursive", ",", "max_attempts", ",", "1", ",", "[", "]", ...
.. versionadded:: Fluorine Execute ``yum-complete-transaction``, which is provided by the ``yum-utils`` package. cleanup_only Specify if the ``--cleanup-only`` option should be supplied. recursive Specify if ``yum-complete-transaction`` should be called recursively (it only completes one transaction at a time). max_attempts If ``recursive`` is ``True``, the maximum times ``yum-complete-transaction`` should be called. .. note:: Recursive calls will stop once ``No unfinished transactions left.`` is in the returned output. .. note:: ``yum-utils`` will already be installed on the minion if the package was installed from the Fedora / EPEL repositories. CLI example: .. code-block:: bash salt '*' pkg.complete_transaction salt '*' pkg.complete_transaction cleanup_only=True salt '*' pkg.complete_transaction recursive=True max_attempts=5
[ "..", "versionadded", "::", "Fluorine" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L3252-L3286
train
saltstack/salt
salt/modules/yumpkg.py
_complete_transaction
def _complete_transaction(cleanup_only, recursive, max_attempts, run_count, cmd_ret_list): ''' .. versionadded:: Fluorine Called from ``complete_transaction`` to protect the arguments used for tail recursion, ``run_count`` and ``cmd_ret_list``. ''' cmd = ['yum-complete-transaction'] if cleanup_only: cmd.append('--cleanup-only') cmd_ret_list.append(__salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False )) if (cmd_ret_list[-1]['retcode'] == salt.defaults.exitcodes.EX_OK and recursive and 'No unfinished transactions left.' not in cmd_ret_list[-1]['stdout']): if run_count >= max_attempts: cmd_ret_list[-1]['retcode'] = salt.defaults.exitcodes.EX_GENERIC log.error('Attempt %s/%s exceeded `max_attempts` for command: `%s`', run_count, max_attempts, ' '.join(cmd)) raise CommandExecutionError('The `max_attempts` limit was reached and unfinished transactions remain.' ' You may wish to increase `max_attempts` or re-execute this module.', info={'results': cmd_ret_list}) else: return _complete_transaction(cleanup_only, recursive, max_attempts, run_count + 1, cmd_ret_list) return cmd_ret_list
python
def _complete_transaction(cleanup_only, recursive, max_attempts, run_count, cmd_ret_list): ''' .. versionadded:: Fluorine Called from ``complete_transaction`` to protect the arguments used for tail recursion, ``run_count`` and ``cmd_ret_list``. ''' cmd = ['yum-complete-transaction'] if cleanup_only: cmd.append('--cleanup-only') cmd_ret_list.append(__salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False )) if (cmd_ret_list[-1]['retcode'] == salt.defaults.exitcodes.EX_OK and recursive and 'No unfinished transactions left.' not in cmd_ret_list[-1]['stdout']): if run_count >= max_attempts: cmd_ret_list[-1]['retcode'] = salt.defaults.exitcodes.EX_GENERIC log.error('Attempt %s/%s exceeded `max_attempts` for command: `%s`', run_count, max_attempts, ' '.join(cmd)) raise CommandExecutionError('The `max_attempts` limit was reached and unfinished transactions remain.' ' You may wish to increase `max_attempts` or re-execute this module.', info={'results': cmd_ret_list}) else: return _complete_transaction(cleanup_only, recursive, max_attempts, run_count + 1, cmd_ret_list) return cmd_ret_list
[ "def", "_complete_transaction", "(", "cleanup_only", ",", "recursive", ",", "max_attempts", ",", "run_count", ",", "cmd_ret_list", ")", ":", "cmd", "=", "[", "'yum-complete-transaction'", "]", "if", "cleanup_only", ":", "cmd", ".", "append", "(", "'--cleanup-only'...
.. versionadded:: Fluorine Called from ``complete_transaction`` to protect the arguments used for tail recursion, ``run_count`` and ``cmd_ret_list``.
[ "..", "versionadded", "::", "Fluorine" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L3289-L3320
train
saltstack/salt
salt/states/boto_route53.py
present
def present(name, value, zone, record_type, ttl=None, identifier=None, region=None, key=None, keyid=None, profile=None, wait_for_sync=True, split_dns=False, private_zone=False): ''' Ensure the Route53 record is present. name Name of the record. value Value of the record. As a special case, you can pass in: `private:<Name tag>` to have the function autodetermine the private IP `public:<Name tag>` to have the function autodetermine the public IP zone The zone to create the record in. record_type The record type (A, NS, MX, TXT, etc.) ttl The time to live for the record. identifier The unique identifier to use for this record. region The 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. wait_for_sync Wait for an INSYNC change status from Route53 before returning success. split_dns Route53 supports parallel public and private DNS zones with the same name. private_zone If using split_dns, specify if this is the private zone. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # If a list is passed in for value, change it to a comma-separated string # So it will work with subsequent boto module calls and string functions if isinstance(value, list): value = ','.join(value) elif value.startswith('private:') or value.startswith('public:'): name_tag = value.split(':', 1)[1] in_states = ('pending', 'rebooting', 'running', 'stopping', 'stopped') r = __salt__['boto_ec2.find_instances'](name=name_tag, return_objs=True, in_states=in_states, profile=profile) if not r: ret['comment'] = 'Error: instance with Name tag {0} not found'.format(name_tag) ret['result'] = False return ret if len(r) > 1: ret['comment'] = 'Error: Name tag {0} matched more than one instance'.format(name_tag) ret['result'] = False return ret instance = r[0] private_ip = getattr(instance, 'private_ip_address', None) public_ip = getattr(instance, 'ip_address', None) if value.startswith('private:'): value = private_ip log.info('Found private IP %s for instance %s', private_ip, name_tag) else: if public_ip is None: ret['comment'] = 'Error: No Public IP assigned to instance with Name {0}'.format(name_tag) ret['result'] = False return ret value = public_ip log.info('Found public IP %s for instance %s', public_ip, name_tag) try: record = __salt__['boto_route53.get_record'](name, zone, record_type, False, region, key, keyid, profile, split_dns, private_zone, identifier) except SaltInvocationError as err: ret['comment'] = 'Error: {0}'.format(err) ret['result'] = False return ret if isinstance(record, dict) and not record: if __opts__['test']: ret['comment'] = 'Route53 record {0} set to be added.'.format(name) ret['result'] = None return ret added = __salt__['boto_route53.add_record'](name, value, zone, record_type, identifier, ttl, region, key, keyid, profile, wait_for_sync, split_dns, private_zone) if added: ret['changes']['old'] = None ret['changes']['new'] = {'name': name, 'value': value, 'record_type': record_type, 'ttl': ttl, 'identifier': identifier} ret['comment'] = 'Added {0} Route53 record.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to add {0} Route53 record.'.format(name) return ret elif record: need_to_update = False # Values can be a comma separated list and some values will end with a # period (even if we set it without one). To easily check this we need # to split and check with the period stripped from the input and what's # in route53. # TODO: figure out if this will cause us problems with some records. _values = [x.rstrip('.') for x in value.split(',')] _r_values = [x.rstrip('.') for x in record['value'].split(',')] _values.sort() _r_values.sort() if _values != _r_values: need_to_update = True if identifier and identifier != record['identifier']: need_to_update = True if ttl and six.text_type(ttl) != six.text_type(record['ttl']): need_to_update = True if need_to_update: if __opts__['test']: ret['comment'] = 'Route53 record {0} set to be updated.'.format(name) ret['result'] = None return ret updated = __salt__['boto_route53.update_record'](name, value, zone, record_type, identifier, ttl, region, key, keyid, profile, wait_for_sync, split_dns, private_zone) if updated: ret['changes']['old'] = record ret['changes']['new'] = {'name': name, 'value': value, 'record_type': record_type, 'ttl': ttl, 'identifier': identifier} ret['comment'] = 'Updated {0} Route53 record.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to update {0} Route53 record.'.format(name) else: ret['comment'] = '{0} exists.'.format(name) return ret
python
def present(name, value, zone, record_type, ttl=None, identifier=None, region=None, key=None, keyid=None, profile=None, wait_for_sync=True, split_dns=False, private_zone=False): ''' Ensure the Route53 record is present. name Name of the record. value Value of the record. As a special case, you can pass in: `private:<Name tag>` to have the function autodetermine the private IP `public:<Name tag>` to have the function autodetermine the public IP zone The zone to create the record in. record_type The record type (A, NS, MX, TXT, etc.) ttl The time to live for the record. identifier The unique identifier to use for this record. region The 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. wait_for_sync Wait for an INSYNC change status from Route53 before returning success. split_dns Route53 supports parallel public and private DNS zones with the same name. private_zone If using split_dns, specify if this is the private zone. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # If a list is passed in for value, change it to a comma-separated string # So it will work with subsequent boto module calls and string functions if isinstance(value, list): value = ','.join(value) elif value.startswith('private:') or value.startswith('public:'): name_tag = value.split(':', 1)[1] in_states = ('pending', 'rebooting', 'running', 'stopping', 'stopped') r = __salt__['boto_ec2.find_instances'](name=name_tag, return_objs=True, in_states=in_states, profile=profile) if not r: ret['comment'] = 'Error: instance with Name tag {0} not found'.format(name_tag) ret['result'] = False return ret if len(r) > 1: ret['comment'] = 'Error: Name tag {0} matched more than one instance'.format(name_tag) ret['result'] = False return ret instance = r[0] private_ip = getattr(instance, 'private_ip_address', None) public_ip = getattr(instance, 'ip_address', None) if value.startswith('private:'): value = private_ip log.info('Found private IP %s for instance %s', private_ip, name_tag) else: if public_ip is None: ret['comment'] = 'Error: No Public IP assigned to instance with Name {0}'.format(name_tag) ret['result'] = False return ret value = public_ip log.info('Found public IP %s for instance %s', public_ip, name_tag) try: record = __salt__['boto_route53.get_record'](name, zone, record_type, False, region, key, keyid, profile, split_dns, private_zone, identifier) except SaltInvocationError as err: ret['comment'] = 'Error: {0}'.format(err) ret['result'] = False return ret if isinstance(record, dict) and not record: if __opts__['test']: ret['comment'] = 'Route53 record {0} set to be added.'.format(name) ret['result'] = None return ret added = __salt__['boto_route53.add_record'](name, value, zone, record_type, identifier, ttl, region, key, keyid, profile, wait_for_sync, split_dns, private_zone) if added: ret['changes']['old'] = None ret['changes']['new'] = {'name': name, 'value': value, 'record_type': record_type, 'ttl': ttl, 'identifier': identifier} ret['comment'] = 'Added {0} Route53 record.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to add {0} Route53 record.'.format(name) return ret elif record: need_to_update = False # Values can be a comma separated list and some values will end with a # period (even if we set it without one). To easily check this we need # to split and check with the period stripped from the input and what's # in route53. # TODO: figure out if this will cause us problems with some records. _values = [x.rstrip('.') for x in value.split(',')] _r_values = [x.rstrip('.') for x in record['value'].split(',')] _values.sort() _r_values.sort() if _values != _r_values: need_to_update = True if identifier and identifier != record['identifier']: need_to_update = True if ttl and six.text_type(ttl) != six.text_type(record['ttl']): need_to_update = True if need_to_update: if __opts__['test']: ret['comment'] = 'Route53 record {0} set to be updated.'.format(name) ret['result'] = None return ret updated = __salt__['boto_route53.update_record'](name, value, zone, record_type, identifier, ttl, region, key, keyid, profile, wait_for_sync, split_dns, private_zone) if updated: ret['changes']['old'] = record ret['changes']['new'] = {'name': name, 'value': value, 'record_type': record_type, 'ttl': ttl, 'identifier': identifier} ret['comment'] = 'Updated {0} Route53 record.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to update {0} Route53 record.'.format(name) else: ret['comment'] = '{0} exists.'.format(name) return ret
[ "def", "present", "(", "name", ",", "value", ",", "zone", ",", "record_type", ",", "ttl", "=", "None", ",", "identifier", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",",...
Ensure the Route53 record is present. name Name of the record. value Value of the record. As a special case, you can pass in: `private:<Name tag>` to have the function autodetermine the private IP `public:<Name tag>` to have the function autodetermine the public IP zone The zone to create the record in. record_type The record type (A, NS, MX, TXT, etc.) ttl The time to live for the record. identifier The unique identifier to use for this record. region The 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. wait_for_sync Wait for an INSYNC change status from Route53 before returning success. split_dns Route53 supports parallel public and private DNS zones with the same name. private_zone If using split_dns, specify if this is the private zone.
[ "Ensure", "the", "Route53", "record", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_route53.py#L99-L256
train
saltstack/salt
salt/states/boto_route53.py
absent
def absent( name, zone, record_type, identifier=None, region=None, key=None, keyid=None, profile=None, wait_for_sync=True, split_dns=False, private_zone=False): ''' Ensure the Route53 record is deleted. name Name of the record. zone The zone to delete the record from. record_type The record type (A, NS, MX, TXT, etc.) identifier An identifier to match for deletion. region The 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. wait_for_sync Wait for an INSYNC change status from Route53. split_dns Route53 supports a public and private DNS zone with the same names. private_zone If using split_dns, specify if this is the private zone. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} record = __salt__['boto_route53.get_record'](name, zone, record_type, False, region, key, keyid, profile, split_dns, private_zone, identifier) if record: if __opts__['test']: ret['comment'] = 'Route53 record {0} set to be deleted.'.format(name) ret['result'] = None return ret deleted = __salt__['boto_route53.delete_record'](name, zone, record_type, identifier, False, region, key, keyid, profile, wait_for_sync, split_dns, private_zone) if deleted: ret['changes']['old'] = record ret['changes']['new'] = None ret['comment'] = 'Deleted {0} Route53 record.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to delete {0} Route53 record.'.format(name) else: ret['comment'] = '{0} does not exist.'.format(name) return ret
python
def absent( name, zone, record_type, identifier=None, region=None, key=None, keyid=None, profile=None, wait_for_sync=True, split_dns=False, private_zone=False): ''' Ensure the Route53 record is deleted. name Name of the record. zone The zone to delete the record from. record_type The record type (A, NS, MX, TXT, etc.) identifier An identifier to match for deletion. region The 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. wait_for_sync Wait for an INSYNC change status from Route53. split_dns Route53 supports a public and private DNS zone with the same names. private_zone If using split_dns, specify if this is the private zone. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} record = __salt__['boto_route53.get_record'](name, zone, record_type, False, region, key, keyid, profile, split_dns, private_zone, identifier) if record: if __opts__['test']: ret['comment'] = 'Route53 record {0} set to be deleted.'.format(name) ret['result'] = None return ret deleted = __salt__['boto_route53.delete_record'](name, zone, record_type, identifier, False, region, key, keyid, profile, wait_for_sync, split_dns, private_zone) if deleted: ret['changes']['old'] = record ret['changes']['new'] = None ret['comment'] = 'Deleted {0} Route53 record.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to delete {0} Route53 record.'.format(name) else: ret['comment'] = '{0} does not exist.'.format(name) return ret
[ "def", "absent", "(", "name", ",", "zone", ",", "record_type", ",", "identifier", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "wait_for_sync", "=", "True", ",", "split...
Ensure the Route53 record is deleted. name Name of the record. zone The zone to delete the record from. record_type The record type (A, NS, MX, TXT, etc.) identifier An identifier to match for deletion. region The 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. wait_for_sync Wait for an INSYNC change status from Route53. split_dns Route53 supports a public and private DNS zone with the same names. private_zone If using split_dns, specify if this is the private zone.
[ "Ensure", "the", "Route53", "record", "is", "deleted", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_route53.py#L263-L341
train
saltstack/salt
salt/states/boto_route53.py
hosted_zone_present
def hosted_zone_present(name, domain_name=None, private_zone=False, caller_ref=None, comment='', vpc_id=None, vpc_name=None, vpc_region=None, region=None, key=None, keyid=None, profile=None): ''' Ensure a hosted zone exists with the given attributes. Note that most things cannot be modified once a zone is created - it must be deleted and re-spun to update these attributes: - private_zone (AWS API limitation). - comment (the appropriate call exists in the AWS API and in boto3, but has not, as of this writing, been added to boto2). - vpc_id (same story - we really need to rewrite this module with boto3) - vpc_name (really just a pointer to vpc_id anyway). - vpc_region (again, supported in boto3 but not boto2). If you need the ability to update these attributes, please use the newer boto3_route53 module instead. name The name of the state definition. domain_name The name of the domain. This must be fully-qualified, terminating with a period. This is the name you have registered with your domain registrar. It is also the name you will delegate from your registrar to the Amazon Route 53 delegation servers returned in response to this request. Defaults to the value of name if not provided. private_zone Set True if creating a private hosted zone. caller_ref A unique string that identifies the request and that allows create_hosted_zone() calls to be retried without the risk of executing the operation twice. This helps ensure idempotency across state calls, but can cause issues if a zone is deleted and then an attempt is made to recreate it with the same caller_ref. If not provided, a unique UUID will be generated at each state run, which avoids the risk of the above (transient) error. This option is generally not needed. Maximum length of 128. comment Any comments you want to include about the hosted zone. vpc_id When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with vpe_name. Ignored when creating a non-private zone. vpc_name When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with vpe_id. Ignored when creating a non-private zone. vpc_region When creating a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from vpc_id or vpc_name, where possible. If this fails, you'll need to provide an explicit value for this option. Ignored when creating a non-private zone. ''' domain_name = domain_name if domain_name else name ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # First translaste vpc_name into a vpc_id if possible if private_zone: if not salt.utils.data.exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('Either vpc_name or vpc_id is required when creating a ' 'private zone.') vpcs = __salt__['boto_vpc.describe_vpcs']( vpc_id=vpc_id, name=vpc_name, region=region, key=key, keyid=keyid, profile=profile).get('vpcs', []) if vpc_region and vpcs: vpcs = [v for v in vpcs if v['region'] == vpc_region] if not vpcs: msg = 'Private zone requested but a VPC matching given criteria not found.' log.error(msg) ret['comment'] = msg ret['result'] = False return ret if len(vpcs) > 1: log.error( 'Private zone requested but multiple VPCs matching given ' 'criteria found: %s', [v['id'] for v in vpcs] ) return None vpc = vpcs[0] if vpc_name: vpc_id = vpc['id'] if not vpc_region: vpc_region = vpc['region'] # Next, see if it (or they) exist at all, anywhere? deets = __salt__['boto_route53.describe_hosted_zones']( domain_name=domain_name, region=region, key=key, keyid=keyid, profile=profile) create = False if not deets: create = True else: # Something exists - now does it match our criteria? if (salt.utils.json.loads(deets['HostedZone']['Config']['PrivateZone']) != private_zone): create = True else: if private_zone: for d in deets.get('VPCs', {}): if (d['VPCId'] == vpc_id and d['VPCRegion'] == vpc_region): create = False break else: create = True if not create: ret['comment'] = 'Hostd Zone {0} already in desired state'.format( domain_name) else: # Until we get modifies in place with boto3, the best option is to # attempt creation and let route53 tell us if we're stepping on # toes. We can't just fail, because some scenarios (think split # horizon DNS) require zones with identical names but different # settings... log.info('A Hosted Zone with name %s already exists, but with ' 'different settings. Will attempt to create the one ' 'requested on the assumption this is what is desired. ' 'This may fail...', domain_name) if create: if caller_ref is None: caller_ref = six.text_type(uuid.uuid4()) if __opts__['test']: ret['comment'] = 'Route53 Hosted Zone {0} set to be added.'.format( domain_name) ret['result'] = None return ret res = __salt__['boto_route53.create_hosted_zone'](domain_name=domain_name, caller_ref=caller_ref, comment=comment, private_zone=private_zone, vpc_id=vpc_id, vpc_region=vpc_region, region=region, key=key, keyid=keyid, profile=profile) if res: msg = 'Hosted Zone {0} successfully created'.format(domain_name) log.info(msg) ret['comment'] = msg ret['changes']['old'] = None ret['changes']['new'] = res else: ret['comment'] = 'Creating Hosted Zone {0} failed'.format( domain_name) ret['result'] = False return ret
python
def hosted_zone_present(name, domain_name=None, private_zone=False, caller_ref=None, comment='', vpc_id=None, vpc_name=None, vpc_region=None, region=None, key=None, keyid=None, profile=None): ''' Ensure a hosted zone exists with the given attributes. Note that most things cannot be modified once a zone is created - it must be deleted and re-spun to update these attributes: - private_zone (AWS API limitation). - comment (the appropriate call exists in the AWS API and in boto3, but has not, as of this writing, been added to boto2). - vpc_id (same story - we really need to rewrite this module with boto3) - vpc_name (really just a pointer to vpc_id anyway). - vpc_region (again, supported in boto3 but not boto2). If you need the ability to update these attributes, please use the newer boto3_route53 module instead. name The name of the state definition. domain_name The name of the domain. This must be fully-qualified, terminating with a period. This is the name you have registered with your domain registrar. It is also the name you will delegate from your registrar to the Amazon Route 53 delegation servers returned in response to this request. Defaults to the value of name if not provided. private_zone Set True if creating a private hosted zone. caller_ref A unique string that identifies the request and that allows create_hosted_zone() calls to be retried without the risk of executing the operation twice. This helps ensure idempotency across state calls, but can cause issues if a zone is deleted and then an attempt is made to recreate it with the same caller_ref. If not provided, a unique UUID will be generated at each state run, which avoids the risk of the above (transient) error. This option is generally not needed. Maximum length of 128. comment Any comments you want to include about the hosted zone. vpc_id When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with vpe_name. Ignored when creating a non-private zone. vpc_name When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with vpe_id. Ignored when creating a non-private zone. vpc_region When creating a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from vpc_id or vpc_name, where possible. If this fails, you'll need to provide an explicit value for this option. Ignored when creating a non-private zone. ''' domain_name = domain_name if domain_name else name ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # First translaste vpc_name into a vpc_id if possible if private_zone: if not salt.utils.data.exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('Either vpc_name or vpc_id is required when creating a ' 'private zone.') vpcs = __salt__['boto_vpc.describe_vpcs']( vpc_id=vpc_id, name=vpc_name, region=region, key=key, keyid=keyid, profile=profile).get('vpcs', []) if vpc_region and vpcs: vpcs = [v for v in vpcs if v['region'] == vpc_region] if not vpcs: msg = 'Private zone requested but a VPC matching given criteria not found.' log.error(msg) ret['comment'] = msg ret['result'] = False return ret if len(vpcs) > 1: log.error( 'Private zone requested but multiple VPCs matching given ' 'criteria found: %s', [v['id'] for v in vpcs] ) return None vpc = vpcs[0] if vpc_name: vpc_id = vpc['id'] if not vpc_region: vpc_region = vpc['region'] # Next, see if it (or they) exist at all, anywhere? deets = __salt__['boto_route53.describe_hosted_zones']( domain_name=domain_name, region=region, key=key, keyid=keyid, profile=profile) create = False if not deets: create = True else: # Something exists - now does it match our criteria? if (salt.utils.json.loads(deets['HostedZone']['Config']['PrivateZone']) != private_zone): create = True else: if private_zone: for d in deets.get('VPCs', {}): if (d['VPCId'] == vpc_id and d['VPCRegion'] == vpc_region): create = False break else: create = True if not create: ret['comment'] = 'Hostd Zone {0} already in desired state'.format( domain_name) else: # Until we get modifies in place with boto3, the best option is to # attempt creation and let route53 tell us if we're stepping on # toes. We can't just fail, because some scenarios (think split # horizon DNS) require zones with identical names but different # settings... log.info('A Hosted Zone with name %s already exists, but with ' 'different settings. Will attempt to create the one ' 'requested on the assumption this is what is desired. ' 'This may fail...', domain_name) if create: if caller_ref is None: caller_ref = six.text_type(uuid.uuid4()) if __opts__['test']: ret['comment'] = 'Route53 Hosted Zone {0} set to be added.'.format( domain_name) ret['result'] = None return ret res = __salt__['boto_route53.create_hosted_zone'](domain_name=domain_name, caller_ref=caller_ref, comment=comment, private_zone=private_zone, vpc_id=vpc_id, vpc_region=vpc_region, region=region, key=key, keyid=keyid, profile=profile) if res: msg = 'Hosted Zone {0} successfully created'.format(domain_name) log.info(msg) ret['comment'] = msg ret['changes']['old'] = None ret['changes']['new'] = res else: ret['comment'] = 'Creating Hosted Zone {0} failed'.format( domain_name) ret['result'] = False return ret
[ "def", "hosted_zone_present", "(", "name", ",", "domain_name", "=", "None", ",", "private_zone", "=", "False", ",", "caller_ref", "=", "None", ",", "comment", "=", "''", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "vpc_region", "=", "N...
Ensure a hosted zone exists with the given attributes. Note that most things cannot be modified once a zone is created - it must be deleted and re-spun to update these attributes: - private_zone (AWS API limitation). - comment (the appropriate call exists in the AWS API and in boto3, but has not, as of this writing, been added to boto2). - vpc_id (same story - we really need to rewrite this module with boto3) - vpc_name (really just a pointer to vpc_id anyway). - vpc_region (again, supported in boto3 but not boto2). If you need the ability to update these attributes, please use the newer boto3_route53 module instead. name The name of the state definition. domain_name The name of the domain. This must be fully-qualified, terminating with a period. This is the name you have registered with your domain registrar. It is also the name you will delegate from your registrar to the Amazon Route 53 delegation servers returned in response to this request. Defaults to the value of name if not provided. private_zone Set True if creating a private hosted zone. caller_ref A unique string that identifies the request and that allows create_hosted_zone() calls to be retried without the risk of executing the operation twice. This helps ensure idempotency across state calls, but can cause issues if a zone is deleted and then an attempt is made to recreate it with the same caller_ref. If not provided, a unique UUID will be generated at each state run, which avoids the risk of the above (transient) error. This option is generally not needed. Maximum length of 128. comment Any comments you want to include about the hosted zone. vpc_id When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with vpe_name. Ignored when creating a non-private zone. vpc_name When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with vpe_id. Ignored when creating a non-private zone. vpc_region When creating a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from vpc_id or vpc_name, where possible. If this fails, you'll need to provide an explicit value for this option. Ignored when creating a non-private zone.
[ "Ensure", "a", "hosted", "zone", "exists", "with", "the", "given", "attributes", ".", "Note", "that", "most", "things", "cannot", "be", "modified", "once", "a", "zone", "is", "created", "-", "it", "must", "be", "deleted", "and", "re", "-", "spun", "to", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_route53.py#L344-L489
train
saltstack/salt
salt/states/boto_route53.py
hosted_zone_absent
def hosted_zone_absent(name, domain_name=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the Route53 Hostes Zone described is absent name The name of the state definition. domain_name The FQDN (including final period) of the zone you wish absent. If not provided, the value of name will be used. ''' domain_name = domain_name if domain_name else name ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} deets = __salt__['boto_route53.describe_hosted_zones']( domain_name=domain_name, region=region, key=key, keyid=keyid, profile=profile) if not deets: ret['comment'] = 'Hosted Zone {0} already absent'.format(domain_name) log.info(ret['comment']) return ret if __opts__['test']: ret['comment'] = 'Route53 Hosted Zone {0} set to be deleted.'.format( domain_name) ret['result'] = None return ret # Not entirely comfortable with this - no safety checks around pub/priv, VPCs # or anything else. But this is all the module function exposes, so hmph. # Inclined to put it on the "wait 'til we port to boto3" pile in any case :) if __salt__['boto_route53.delete_zone']( zone=domain_name, region=region, key=key, keyid=keyid, profile=profile): ret['comment'] = 'Route53 Hosted Zone {0} deleted'.format(domain_name) log.info(ret['comment']) ret['changes']['old'] = deets ret['changes']['new'] = None return ret
python
def hosted_zone_absent(name, domain_name=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the Route53 Hostes Zone described is absent name The name of the state definition. domain_name The FQDN (including final period) of the zone you wish absent. If not provided, the value of name will be used. ''' domain_name = domain_name if domain_name else name ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} deets = __salt__['boto_route53.describe_hosted_zones']( domain_name=domain_name, region=region, key=key, keyid=keyid, profile=profile) if not deets: ret['comment'] = 'Hosted Zone {0} already absent'.format(domain_name) log.info(ret['comment']) return ret if __opts__['test']: ret['comment'] = 'Route53 Hosted Zone {0} set to be deleted.'.format( domain_name) ret['result'] = None return ret # Not entirely comfortable with this - no safety checks around pub/priv, VPCs # or anything else. But this is all the module function exposes, so hmph. # Inclined to put it on the "wait 'til we port to boto3" pile in any case :) if __salt__['boto_route53.delete_zone']( zone=domain_name, region=region, key=key, keyid=keyid, profile=profile): ret['comment'] = 'Route53 Hosted Zone {0} deleted'.format(domain_name) log.info(ret['comment']) ret['changes']['old'] = deets ret['changes']['new'] = None return ret
[ "def", "hosted_zone_absent", "(", "name", ",", "domain_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "domain_name", "=", "domain_name", "if", "domain_name", "els...
Ensure the Route53 Hostes Zone described is absent name The name of the state definition. domain_name The FQDN (including final period) of the zone you wish absent. If not provided, the value of name will be used.
[ "Ensure", "the", "Route53", "Hostes", "Zone", "described", "is", "absent" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_route53.py#L492-L532
train
saltstack/salt
salt/utils/ssdp.py
SSDPBase.get_self_ip
def get_self_ip(): ''' Find out localhost outside IP. :return: ''' sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sck.connect(('1.255.255.255', 1)) # Does not needs to be reachable ip_addr = sck.getsockname()[0] except Exception: ip_addr = socket.gethostbyname(socket.gethostname()) finally: sck.close() return ip_addr
python
def get_self_ip(): ''' Find out localhost outside IP. :return: ''' sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sck.connect(('1.255.255.255', 1)) # Does not needs to be reachable ip_addr = sck.getsockname()[0] except Exception: ip_addr = socket.gethostbyname(socket.gethostname()) finally: sck.close() return ip_addr
[ "def", "get_self_ip", "(", ")", ":", "sck", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "try", ":", "sck", ".", "connect", "(", "(", "'1.255.255.255'", ",", "1", ")", ")", "# Does not needs to be re...
Find out localhost outside IP. :return:
[ "Find", "out", "localhost", "outside", "IP", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L89-L103
train
saltstack/salt
salt/utils/ssdp.py
SSDPFactory._sendto
def _sendto(self, data, addr=None, attempts=10): ''' On multi-master environments, running on the same machine, transport sending to the destination can be allowed only at once. Since every machine will immediately respond, high chance to get sending fired at the same time, which will result to a PermissionError at socket level. We are attempting to send it in a different time. :param data: :param addr: :return: ''' tries = 0 slp_time = lambda: 0.5 / random.randint(10, 30) slp = slp_time() while tries < attempts: try: self.transport.sendto(data, addr=addr) self.log.debug('Sent successfully') return except AttributeError as ex: self.log.debug('Permission error: %s', ex) time.sleep(slp) tries += 1 slp += slp_time()
python
def _sendto(self, data, addr=None, attempts=10): ''' On multi-master environments, running on the same machine, transport sending to the destination can be allowed only at once. Since every machine will immediately respond, high chance to get sending fired at the same time, which will result to a PermissionError at socket level. We are attempting to send it in a different time. :param data: :param addr: :return: ''' tries = 0 slp_time = lambda: 0.5 / random.randint(10, 30) slp = slp_time() while tries < attempts: try: self.transport.sendto(data, addr=addr) self.log.debug('Sent successfully') return except AttributeError as ex: self.log.debug('Permission error: %s', ex) time.sleep(slp) tries += 1 slp += slp_time()
[ "def", "_sendto", "(", "self", ",", "data", ",", "addr", "=", "None", ",", "attempts", "=", "10", ")", ":", "tries", "=", "0", "slp_time", "=", "lambda", ":", "0.5", "/", "random", ".", "randint", "(", "10", ",", "30", ")", "slp", "=", "slp_time"...
On multi-master environments, running on the same machine, transport sending to the destination can be allowed only at once. Since every machine will immediately respond, high chance to get sending fired at the same time, which will result to a PermissionError at socket level. We are attempting to send it in a different time. :param data: :param addr: :return:
[ "On", "multi", "-", "master", "environments", "running", "on", "the", "same", "machine", "transport", "sending", "to", "the", "destination", "can", "be", "allowed", "only", "at", "once", ".", "Since", "every", "machine", "will", "immediately", "respond", "high...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L141-L165
train
saltstack/salt
salt/utils/ssdp.py
SSDPFactory.datagram_received
def datagram_received(self, data, addr): ''' On datagram receive. :param data: :param addr: :return: ''' message = salt.utils.stringutils.to_unicode(data) if message.startswith(self.signature): try: timestamp = float(message[len(self.signature):]) except (TypeError, ValueError): self.log.debug( 'Received invalid timestamp in package from %s:%s', *addr ) if self.disable_hidden: self._sendto('{0}:E:{1}'.format(self.signature, 'Invalid timestamp'), addr) return if datetime.datetime.fromtimestamp(timestamp) < (datetime.datetime.now() - datetime.timedelta(seconds=20)): if self.disable_hidden: self._sendto('{0}:E:{1}'.format(self.signature, 'Timestamp is too old'), addr) self.log.debug('Received outdated package from %s:%s', *addr) return self.log.debug('Received "%s" from %s:%s', message, *addr) self._sendto( salt.utils.stringutils.to_bytes(str('{0}:@:{1}').format( # future lint: disable=blacklisted-function self.signature, salt.utils.json.dumps(self.answer, _json_module=_json) )), addr ) else: if self.disable_hidden: self._sendto( salt.utils.stringutils.to_bytes( '{0}:E:{1}'.format(self.signature, 'Invalid packet signature'), addr ) ) self.log.debug('Received bad signature from %s:%s', *addr)
python
def datagram_received(self, data, addr): ''' On datagram receive. :param data: :param addr: :return: ''' message = salt.utils.stringutils.to_unicode(data) if message.startswith(self.signature): try: timestamp = float(message[len(self.signature):]) except (TypeError, ValueError): self.log.debug( 'Received invalid timestamp in package from %s:%s', *addr ) if self.disable_hidden: self._sendto('{0}:E:{1}'.format(self.signature, 'Invalid timestamp'), addr) return if datetime.datetime.fromtimestamp(timestamp) < (datetime.datetime.now() - datetime.timedelta(seconds=20)): if self.disable_hidden: self._sendto('{0}:E:{1}'.format(self.signature, 'Timestamp is too old'), addr) self.log.debug('Received outdated package from %s:%s', *addr) return self.log.debug('Received "%s" from %s:%s', message, *addr) self._sendto( salt.utils.stringutils.to_bytes(str('{0}:@:{1}').format( # future lint: disable=blacklisted-function self.signature, salt.utils.json.dumps(self.answer, _json_module=_json) )), addr ) else: if self.disable_hidden: self._sendto( salt.utils.stringutils.to_bytes( '{0}:E:{1}'.format(self.signature, 'Invalid packet signature'), addr ) ) self.log.debug('Received bad signature from %s:%s', *addr)
[ "def", "datagram_received", "(", "self", ",", "data", ",", "addr", ")", ":", "message", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "data", ")", "if", "message", ".", "startswith", "(", "self", ".", "signature", ")", ":", "tr...
On datagram receive. :param data: :param addr: :return:
[ "On", "datagram", "receive", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L167-L210
train
saltstack/salt
salt/utils/ssdp.py
SSDPDiscoveryServer.create_datagram_endpoint
def create_datagram_endpoint(loop, protocol_factory, local_addr=None, remote_addr=None, family=0, proto=0, flags=0): ''' Create datagram connection. Based on code from Python 3.5 version, this method is used only in Python 2.7+ versions, since Trollius library did not ported UDP packets broadcast. ''' if not (local_addr or remote_addr): if not family: raise ValueError('unexpected address family') addr_pairs_info = (((family, proto), (None, None)),) else: addr_infos = OrderedDict() for idx, addr in ((0, local_addr), (1, remote_addr)): if addr is not None: assert isinstance(addr, tuple) and len(addr) == 2, '2-tuple is expected' infos = yield asyncio.coroutines.From(loop.getaddrinfo( *addr, family=family, type=socket.SOCK_DGRAM, proto=proto, flags=flags)) if not infos: raise socket.error('getaddrinfo() returned empty list') for fam, _, pro, _, address in infos: key = (fam, pro) if key not in addr_infos: addr_infos[key] = [None, None] addr_infos[key][idx] = address addr_pairs_info = [ (key, addr_pair) for key, addr_pair in addr_infos.items() if not ((local_addr and addr_pair[0] is None) or (remote_addr and addr_pair[1] is None))] if not addr_pairs_info: raise ValueError('can not get address information') exceptions = [] for ((family, proto), (local_address, remote_address)) in addr_pairs_info: sock = r_addr = None try: sock = socket.socket(family=family, type=socket.SOCK_DGRAM, proto=proto) for opt in [socket.SO_REUSEADDR, socket.SO_BROADCAST]: sock.setsockopt(socket.SOL_SOCKET, opt, 1) sock.setblocking(False) if local_addr: sock.bind(local_address) if remote_addr: yield asyncio.coroutines.From(loop.sock_connect(sock, remote_address)) r_addr = remote_address except socket.error as exc: if sock is not None: sock.close() exceptions.append(exc) except Exception: if sock is not None: sock.close() raise else: break else: raise exceptions[0] protocol = protocol_factory() waiter = asyncio.futures.Future(loop=loop) transport = loop._make_datagram_transport(sock, protocol, r_addr, waiter) try: yield asyncio.coroutines.From(waiter) except Exception: transport.close() raise raise asyncio.coroutines.Return(transport, protocol)
python
def create_datagram_endpoint(loop, protocol_factory, local_addr=None, remote_addr=None, family=0, proto=0, flags=0): ''' Create datagram connection. Based on code from Python 3.5 version, this method is used only in Python 2.7+ versions, since Trollius library did not ported UDP packets broadcast. ''' if not (local_addr or remote_addr): if not family: raise ValueError('unexpected address family') addr_pairs_info = (((family, proto), (None, None)),) else: addr_infos = OrderedDict() for idx, addr in ((0, local_addr), (1, remote_addr)): if addr is not None: assert isinstance(addr, tuple) and len(addr) == 2, '2-tuple is expected' infos = yield asyncio.coroutines.From(loop.getaddrinfo( *addr, family=family, type=socket.SOCK_DGRAM, proto=proto, flags=flags)) if not infos: raise socket.error('getaddrinfo() returned empty list') for fam, _, pro, _, address in infos: key = (fam, pro) if key not in addr_infos: addr_infos[key] = [None, None] addr_infos[key][idx] = address addr_pairs_info = [ (key, addr_pair) for key, addr_pair in addr_infos.items() if not ((local_addr and addr_pair[0] is None) or (remote_addr and addr_pair[1] is None))] if not addr_pairs_info: raise ValueError('can not get address information') exceptions = [] for ((family, proto), (local_address, remote_address)) in addr_pairs_info: sock = r_addr = None try: sock = socket.socket(family=family, type=socket.SOCK_DGRAM, proto=proto) for opt in [socket.SO_REUSEADDR, socket.SO_BROADCAST]: sock.setsockopt(socket.SOL_SOCKET, opt, 1) sock.setblocking(False) if local_addr: sock.bind(local_address) if remote_addr: yield asyncio.coroutines.From(loop.sock_connect(sock, remote_address)) r_addr = remote_address except socket.error as exc: if sock is not None: sock.close() exceptions.append(exc) except Exception: if sock is not None: sock.close() raise else: break else: raise exceptions[0] protocol = protocol_factory() waiter = asyncio.futures.Future(loop=loop) transport = loop._make_datagram_transport(sock, protocol, r_addr, waiter) try: yield asyncio.coroutines.From(waiter) except Exception: transport.close() raise raise asyncio.coroutines.Return(transport, protocol)
[ "def", "create_datagram_endpoint", "(", "loop", ",", "protocol_factory", ",", "local_addr", "=", "None", ",", "remote_addr", "=", "None", ",", "family", "=", "0", ",", "proto", "=", "0", ",", "flags", "=", "0", ")", ":", "if", "not", "(", "local_addr", ...
Create datagram connection. Based on code from Python 3.5 version, this method is used only in Python 2.7+ versions, since Trollius library did not ported UDP packets broadcast.
[ "Create", "datagram", "connection", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L238-L305
train
saltstack/salt
salt/utils/ssdp.py
SSDPDiscoveryServer.run
def run(self): ''' Run server. :return: ''' listen_ip = self._config.get(self.LISTEN_IP, self.DEFAULTS[self.LISTEN_IP]) port = self._config.get(self.PORT, self.DEFAULTS[self.PORT]) self.log.info('Starting service discovery listener on udp://%s:%s', listen_ip, port) loop = asyncio.get_event_loop() protocol = SSDPFactory(answer=self._config[self.ANSWER]) if asyncio.ported: transport, protocol = loop.run_until_complete( SSDPDiscoveryServer.create_datagram_endpoint(loop, protocol, local_addr=(listen_ip, port))) else: transport, protocol = loop.run_until_complete( loop.create_datagram_endpoint(protocol, local_addr=(listen_ip, port), allow_broadcast=True)) try: loop.run_forever() finally: self.log.info('Stopping service discovery listener.') transport.close() loop.close()
python
def run(self): ''' Run server. :return: ''' listen_ip = self._config.get(self.LISTEN_IP, self.DEFAULTS[self.LISTEN_IP]) port = self._config.get(self.PORT, self.DEFAULTS[self.PORT]) self.log.info('Starting service discovery listener on udp://%s:%s', listen_ip, port) loop = asyncio.get_event_loop() protocol = SSDPFactory(answer=self._config[self.ANSWER]) if asyncio.ported: transport, protocol = loop.run_until_complete( SSDPDiscoveryServer.create_datagram_endpoint(loop, protocol, local_addr=(listen_ip, port))) else: transport, protocol = loop.run_until_complete( loop.create_datagram_endpoint(protocol, local_addr=(listen_ip, port), allow_broadcast=True)) try: loop.run_forever() finally: self.log.info('Stopping service discovery listener.') transport.close() loop.close()
[ "def", "run", "(", "self", ")", ":", "listen_ip", "=", "self", ".", "_config", ".", "get", "(", "self", ".", "LISTEN_IP", ",", "self", ".", "DEFAULTS", "[", "self", ".", "LISTEN_IP", "]", ")", "port", "=", "self", ".", "_config", ".", "get", "(", ...
Run server. :return:
[ "Run", "server", ".", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L307-L328
train
saltstack/salt
salt/utils/ssdp.py
SSDPDiscoveryClient._query
def _query(self): ''' Query the broadcast for defined services. :return: ''' query = salt.utils.stringutils.to_bytes( "{}{}".format(self.signature, time.time())) self._socket.sendto(query, ('<broadcast>', self.port)) return query
python
def _query(self): ''' Query the broadcast for defined services. :return: ''' query = salt.utils.stringutils.to_bytes( "{}{}".format(self.signature, time.time())) self._socket.sendto(query, ('<broadcast>', self.port)) return query
[ "def", "_query", "(", "self", ")", ":", "query", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_bytes", "(", "\"{}{}\"", ".", "format", "(", "self", ".", "signature", ",", "time", ".", "time", "(", ")", ")", ")", "self", ".", "_socket", "....
Query the broadcast for defined services. :return:
[ "Query", "the", "broadcast", "for", "defined", "services", ".", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L355-L364
train
saltstack/salt
salt/utils/ssdp.py
SSDPDiscoveryClient._collect_masters_map
def _collect_masters_map(self, response): ''' Collect masters map from the network. :return: ''' while True: try: data, addr = self._socket.recvfrom(0x400) if data: if addr not in response: response[addr] = [] response[addr].append(data) else: break except Exception as err: if not response: self.log.error('Discovery master collection failure: %s', err) break
python
def _collect_masters_map(self, response): ''' Collect masters map from the network. :return: ''' while True: try: data, addr = self._socket.recvfrom(0x400) if data: if addr not in response: response[addr] = [] response[addr].append(data) else: break except Exception as err: if not response: self.log.error('Discovery master collection failure: %s', err) break
[ "def", "_collect_masters_map", "(", "self", ",", "response", ")", ":", "while", "True", ":", "try", ":", "data", ",", "addr", "=", "self", ".", "_socket", ".", "recvfrom", "(", "0x400", ")", "if", "data", ":", "if", "addr", "not", "in", "response", "...
Collect masters map from the network. :return:
[ "Collect", "masters", "map", "from", "the", "network", ".", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L366-L383
train
saltstack/salt
salt/utils/ssdp.py
SSDPDiscoveryClient.discover
def discover(self): ''' Gather the information of currently declared servers. :return: ''' response = {} masters = {} self.log.info("Looking for a server discovery") self._query() self._collect_masters_map(response) if not response: msg = 'No master has been discovered.' self.log.info(msg) else: for addr, descriptions in response.items(): for data in descriptions: # Several masters can run at the same machine. msg = salt.utils.stringutils.to_unicode(data) if msg.startswith(self.signature): msg = msg.split(self.signature)[-1] self.log.debug( "Service announcement at '%s:%s'. Response: '%s'", addr[0], addr[1], msg ) if ':E:' in msg: err = msg.split(':E:')[-1] self.log.error( 'Error response from the service publisher at %s: %s', addr, err ) if "timestamp" in err: self.log.error('Publisher sent shifted timestamp from %s', addr) else: if addr not in masters: masters[addr] = [] masters[addr].append( salt.utils.json.loads(msg.split(':@:')[-1], _json_module=_json) ) return masters
python
def discover(self): ''' Gather the information of currently declared servers. :return: ''' response = {} masters = {} self.log.info("Looking for a server discovery") self._query() self._collect_masters_map(response) if not response: msg = 'No master has been discovered.' self.log.info(msg) else: for addr, descriptions in response.items(): for data in descriptions: # Several masters can run at the same machine. msg = salt.utils.stringutils.to_unicode(data) if msg.startswith(self.signature): msg = msg.split(self.signature)[-1] self.log.debug( "Service announcement at '%s:%s'. Response: '%s'", addr[0], addr[1], msg ) if ':E:' in msg: err = msg.split(':E:')[-1] self.log.error( 'Error response from the service publisher at %s: %s', addr, err ) if "timestamp" in err: self.log.error('Publisher sent shifted timestamp from %s', addr) else: if addr not in masters: masters[addr] = [] masters[addr].append( salt.utils.json.loads(msg.split(':@:')[-1], _json_module=_json) ) return masters
[ "def", "discover", "(", "self", ")", ":", "response", "=", "{", "}", "masters", "=", "{", "}", "self", ".", "log", ".", "info", "(", "\"Looking for a server discovery\"", ")", "self", ".", "_query", "(", ")", "self", ".", "_collect_masters_map", "(", "re...
Gather the information of currently declared servers. :return:
[ "Gather", "the", "information", "of", "currently", "declared", "servers", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L385-L423
train
saltstack/salt
salt/states/zabbix_user.py
admin_password_present
def admin_password_present(name, password=None, **kwargs): ''' Initial change of Zabbix Admin password to password taken from one of the sources (only the most prioritized one): 1. 'password' parameter 2. '_connection_password' parameter 3. pillar 'zabbix.password' setting 1) Tries to log in as Admin with password found in state password parameter or _connection_password or pillar or default zabbix password in this precise order, if any of them is present. 2) If one of above passwords matches, it tries to change the password to the most prioritized one. 3) If not able to connect with any password then it fails. :param name: Just a name of state :param password: Optional - desired password for Admin to be set :param _connection_user: Optional - Ignored in this state (always assumed 'Admin') :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) .. code-block:: yaml # password taken from pillar or _connection_password zabbix-admin-password: zabbix_user.admin_password_present # directly set password zabbix-admin-password: zabbix_user.admin_password_present: - password: SECRET_PASS ''' dry_run = __opts__['test'] default_zabbix_user = 'Admin' default_zabbix_password = 'zabbix' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} passwords = [] connection_args = {} connection_args['_connection_user'] = default_zabbix_user if '_connection_url' in kwargs: connection_args['_connection_url'] = kwargs['_connection_url'] config_password = __salt__['config.option']('zabbix.password', None) if config_password: passwords.append(config_password) if '_connection_password' in kwargs: passwords.append(kwargs['_connection_password']) if password: passwords.append(password) # get unique list in preserved order and reverse it seen = set() unique_passwords = [six.text_type(x) for x in passwords if x not in seen and not seen.add(x)] unique_passwords.reverse() if not unique_passwords: ret['comment'] = 'Could not find any Zabbix Admin password setting! See documentation.' return ret else: desired_password = unique_passwords[0] unique_passwords.append(default_zabbix_password) for pwd in unique_passwords: connection_args['_connection_password'] = pwd try: user_get = __salt__['zabbix.user_get'](default_zabbix_user, **connection_args) except SaltException as err: if 'Login name or password is incorrect' in six.text_type(err): user_get = False else: raise if user_get: if pwd == desired_password: ret['result'] = True ret['comment'] = 'Admin password is correct.' return ret else: break if user_get: if not dry_run: user_update = __salt__['zabbix.user_update'](user_get[0]['userid'], passwd=desired_password, **connection_args) if user_update: ret['result'] = True ret['changes']['passwd'] = 'changed to \'' + six.text_type(desired_password) + '\'' else: ret['result'] = None ret['comment'] = 'Password for user ' + six.text_type(default_zabbix_user) \ + ' updated to \'' + six.text_type(desired_password) + '\'' return ret
python
def admin_password_present(name, password=None, **kwargs): ''' Initial change of Zabbix Admin password to password taken from one of the sources (only the most prioritized one): 1. 'password' parameter 2. '_connection_password' parameter 3. pillar 'zabbix.password' setting 1) Tries to log in as Admin with password found in state password parameter or _connection_password or pillar or default zabbix password in this precise order, if any of them is present. 2) If one of above passwords matches, it tries to change the password to the most prioritized one. 3) If not able to connect with any password then it fails. :param name: Just a name of state :param password: Optional - desired password for Admin to be set :param _connection_user: Optional - Ignored in this state (always assumed 'Admin') :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) .. code-block:: yaml # password taken from pillar or _connection_password zabbix-admin-password: zabbix_user.admin_password_present # directly set password zabbix-admin-password: zabbix_user.admin_password_present: - password: SECRET_PASS ''' dry_run = __opts__['test'] default_zabbix_user = 'Admin' default_zabbix_password = 'zabbix' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} passwords = [] connection_args = {} connection_args['_connection_user'] = default_zabbix_user if '_connection_url' in kwargs: connection_args['_connection_url'] = kwargs['_connection_url'] config_password = __salt__['config.option']('zabbix.password', None) if config_password: passwords.append(config_password) if '_connection_password' in kwargs: passwords.append(kwargs['_connection_password']) if password: passwords.append(password) # get unique list in preserved order and reverse it seen = set() unique_passwords = [six.text_type(x) for x in passwords if x not in seen and not seen.add(x)] unique_passwords.reverse() if not unique_passwords: ret['comment'] = 'Could not find any Zabbix Admin password setting! See documentation.' return ret else: desired_password = unique_passwords[0] unique_passwords.append(default_zabbix_password) for pwd in unique_passwords: connection_args['_connection_password'] = pwd try: user_get = __salt__['zabbix.user_get'](default_zabbix_user, **connection_args) except SaltException as err: if 'Login name or password is incorrect' in six.text_type(err): user_get = False else: raise if user_get: if pwd == desired_password: ret['result'] = True ret['comment'] = 'Admin password is correct.' return ret else: break if user_get: if not dry_run: user_update = __salt__['zabbix.user_update'](user_get[0]['userid'], passwd=desired_password, **connection_args) if user_update: ret['result'] = True ret['changes']['passwd'] = 'changed to \'' + six.text_type(desired_password) + '\'' else: ret['result'] = None ret['comment'] = 'Password for user ' + six.text_type(default_zabbix_user) \ + ' updated to \'' + six.text_type(desired_password) + '\'' return ret
[ "def", "admin_password_present", "(", "name", ",", "password", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dry_run", "=", "__opts__", "[", "'test'", "]", "default_zabbix_user", "=", "'Admin'", "default_zabbix_password", "=", "'zabbix'", "ret", "=", "{", ...
Initial change of Zabbix Admin password to password taken from one of the sources (only the most prioritized one): 1. 'password' parameter 2. '_connection_password' parameter 3. pillar 'zabbix.password' setting 1) Tries to log in as Admin with password found in state password parameter or _connection_password or pillar or default zabbix password in this precise order, if any of them is present. 2) If one of above passwords matches, it tries to change the password to the most prioritized one. 3) If not able to connect with any password then it fails. :param name: Just a name of state :param password: Optional - desired password for Admin to be set :param _connection_user: Optional - Ignored in this state (always assumed 'Admin') :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) .. code-block:: yaml # password taken from pillar or _connection_password zabbix-admin-password: zabbix_user.admin_password_present # directly set password zabbix-admin-password: zabbix_user.admin_password_present: - password: SECRET_PASS
[ "Initial", "change", "of", "Zabbix", "Admin", "password", "to", "password", "taken", "from", "one", "of", "the", "sources", "(", "only", "the", "most", "prioritized", "one", ")", ":", "1", ".", "password", "parameter", "2", ".", "_connection_password", "para...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_user.py#L27-L118
train
saltstack/salt
salt/states/zabbix_user.py
present
def present(alias, passwd, usrgrps, medias=None, password_reset=False, **kwargs): ''' Ensures that the user exists, eventually creates new user. NOTE: use argument firstname instead of name to not mess values with name from salt sls. .. versionadded:: 2016.3.0 :param alias: user alias :param passwd: user's password :param usrgrps: user groups to add the user to :param medias: Optional - user's medias to create :param password_reset: whether or not to reset password at update :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess \ with value supplied from Salt sls file. .. code-block:: yaml make_user: zabbix_user.present: - alias: George - passwd: donottellanyonE@456x - password_reset: True - usrgrps: - 13 - 7 - medias: - me@example.com: - mediatype: mail - period: '1-7,00:00-24:00' - severity: NIWAHD - make_jabber: - active: true - mediatype: jabber - period: '1-5,08:00-19:00' - sendto: jabbera@example.com - text_me_morning_disabled: - active: false - mediatype: sms - period: '1-5,09:30-10:00' - severity: D - sendto: '+42032132588568' ''' if medias is None: medias = [] connection_args = {} if '_connection_user' in kwargs: connection_args['_connection_user'] = kwargs['_connection_user'] if '_connection_password' in kwargs: connection_args['_connection_password'] = kwargs['_connection_password'] if '_connection_url' in kwargs: connection_args['_connection_url'] = kwargs['_connection_url'] ret = {'name': alias, 'changes': {}, 'result': False, 'comment': ''} # Comment and change messages comment_user_created = 'User {0} created.'.format(alias) comment_user_updated = 'User {0} updated.'.format(alias) comment_user_notcreated = 'Unable to create user: {0}. '.format(alias) comment_user_exists = 'User {0} already exists.'.format(alias) changes_user_created = {alias: {'old': 'User {0} does not exist.'.format(alias), 'new': 'User {0} created.'.format(alias), } } def _media_format(medias_data): ''' Formats medias from SLS file into valid JSON usable for zabbix API. Completes JSON with default values. :param medias_data: list of media data from SLS file ''' if not medias_data: return list() medias_json = loads(dumps(medias_data)) medias_attr = ('active', 'mediatype', 'period', 'severity', 'sendto') media_type = {'mail': 1, 'jabber': 2, 'sms': 3} media_severities = ('D', 'H', 'A', 'W', 'I', 'N') medias_dict = dict() for media in medias_json: for med in media: medias_dict[med] = dict() for medattr in media[med]: for key, value in medattr.items(): if key in medias_attr: medias_dict[med][key] = value medias_list = list() for key, value in medias_dict.items(): # Load media values or default values active = '0' if six.text_type(value.get('active', 'true')).lower() == 'true' else '1' mediatype_sls = six.text_type(value.get('mediatype', 'mail')).lower() mediatypeid = six.text_type(media_type.get(mediatype_sls, 1)) period = value.get('period', '1-7,00:00-24:00') sendto = value.get('sendto', key) severity_sls = value.get('severity', 'HD') severity_bin = six.text_type() for sev in media_severities: if sev in severity_sls: severity_bin += '1' else: severity_bin += '0' severity = six.text_type(int(severity_bin, 2)) medias_list.append({'active': active, 'mediatypeid': mediatypeid, 'period': period, 'sendto': sendto, 'severity': severity}) return medias_list user_exists = __salt__['zabbix.user_exists'](alias, **connection_args) if user_exists: user = __salt__['zabbix.user_get'](alias, **connection_args)[0] userid = user['userid'] update_usrgrps = False update_medias = False usergroups = __salt__['zabbix.usergroup_get'](userids=userid, **connection_args) cur_usrgrps = list() for usergroup in usergroups: cur_usrgrps.append(int(usergroup['usrgrpid'])) if set(cur_usrgrps) != set(usrgrps): update_usrgrps = True user_medias = __salt__['zabbix.user_getmedia'](userid, **connection_args) medias_formated = _media_format(medias) if user_medias: user_medias_copy = deepcopy(user_medias) for user_med in user_medias_copy: user_med.pop('userid') user_med.pop('mediaid') media_diff = [x for x in medias_formated if x not in user_medias_copy] + \ [y for y in user_medias_copy if y not in medias_formated] if media_diff: update_medias = True elif not user_medias and medias: update_medias = True # Dry run, test=true mode if __opts__['test']: if user_exists: if update_usrgrps or password_reset or update_medias: ret['result'] = None ret['comment'] = comment_user_updated else: ret['result'] = True ret['comment'] = comment_user_exists else: ret['result'] = None ret['comment'] = comment_user_created error = [] if user_exists: ret['result'] = True if update_usrgrps or password_reset or update_medias: ret['comment'] = comment_user_updated if update_usrgrps: __salt__['zabbix.user_update'](userid, usrgrps=usrgrps, **connection_args) updated_groups = __salt__['zabbix.usergroup_get'](userids=userid, **connection_args) cur_usrgrps = list() for usergroup in updated_groups: cur_usrgrps.append(int(usergroup['usrgrpid'])) usrgrp_diff = list(set(usrgrps) - set(cur_usrgrps)) if usrgrp_diff: error.append('Unable to update grpup(s): {0}'.format(usrgrp_diff)) ret['changes']['usrgrps'] = six.text_type(updated_groups) if password_reset: updated_password = __salt__['zabbix.user_update'](userid, passwd=passwd, **connection_args) if 'error' in updated_password: error.append(updated_groups['error']) else: ret['changes']['passwd'] = 'updated' if update_medias: for user_med in user_medias: deletedmed = __salt__['zabbix.user_deletemedia'](user_med['mediaid'], **connection_args) if 'error' in deletedmed: error.append(deletedmed['error']) for media in medias_formated: updatemed = __salt__['zabbix.user_addmedia'](userids=userid, active=media['active'], mediatypeid=media['mediatypeid'], period=media['period'], sendto=media['sendto'], severity=media['severity'], **connection_args) if 'error' in updatemed: error.append(updatemed['error']) ret['changes']['medias'] = six.text_type(medias_formated) else: ret['comment'] = comment_user_exists else: user_create = __salt__['zabbix.user_create'](alias, passwd, usrgrps, **kwargs) if 'error' not in user_create: ret['result'] = True ret['comment'] = comment_user_created ret['changes'] = changes_user_created else: ret['result'] = False ret['comment'] = comment_user_notcreated + six.text_type(user_create['error']) # error detected if error: ret['changes'] = {} ret['result'] = False ret['comment'] = six.text_type(error) return ret
python
def present(alias, passwd, usrgrps, medias=None, password_reset=False, **kwargs): ''' Ensures that the user exists, eventually creates new user. NOTE: use argument firstname instead of name to not mess values with name from salt sls. .. versionadded:: 2016.3.0 :param alias: user alias :param passwd: user's password :param usrgrps: user groups to add the user to :param medias: Optional - user's medias to create :param password_reset: whether or not to reset password at update :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess \ with value supplied from Salt sls file. .. code-block:: yaml make_user: zabbix_user.present: - alias: George - passwd: donottellanyonE@456x - password_reset: True - usrgrps: - 13 - 7 - medias: - me@example.com: - mediatype: mail - period: '1-7,00:00-24:00' - severity: NIWAHD - make_jabber: - active: true - mediatype: jabber - period: '1-5,08:00-19:00' - sendto: jabbera@example.com - text_me_morning_disabled: - active: false - mediatype: sms - period: '1-5,09:30-10:00' - severity: D - sendto: '+42032132588568' ''' if medias is None: medias = [] connection_args = {} if '_connection_user' in kwargs: connection_args['_connection_user'] = kwargs['_connection_user'] if '_connection_password' in kwargs: connection_args['_connection_password'] = kwargs['_connection_password'] if '_connection_url' in kwargs: connection_args['_connection_url'] = kwargs['_connection_url'] ret = {'name': alias, 'changes': {}, 'result': False, 'comment': ''} # Comment and change messages comment_user_created = 'User {0} created.'.format(alias) comment_user_updated = 'User {0} updated.'.format(alias) comment_user_notcreated = 'Unable to create user: {0}. '.format(alias) comment_user_exists = 'User {0} already exists.'.format(alias) changes_user_created = {alias: {'old': 'User {0} does not exist.'.format(alias), 'new': 'User {0} created.'.format(alias), } } def _media_format(medias_data): ''' Formats medias from SLS file into valid JSON usable for zabbix API. Completes JSON with default values. :param medias_data: list of media data from SLS file ''' if not medias_data: return list() medias_json = loads(dumps(medias_data)) medias_attr = ('active', 'mediatype', 'period', 'severity', 'sendto') media_type = {'mail': 1, 'jabber': 2, 'sms': 3} media_severities = ('D', 'H', 'A', 'W', 'I', 'N') medias_dict = dict() for media in medias_json: for med in media: medias_dict[med] = dict() for medattr in media[med]: for key, value in medattr.items(): if key in medias_attr: medias_dict[med][key] = value medias_list = list() for key, value in medias_dict.items(): # Load media values or default values active = '0' if six.text_type(value.get('active', 'true')).lower() == 'true' else '1' mediatype_sls = six.text_type(value.get('mediatype', 'mail')).lower() mediatypeid = six.text_type(media_type.get(mediatype_sls, 1)) period = value.get('period', '1-7,00:00-24:00') sendto = value.get('sendto', key) severity_sls = value.get('severity', 'HD') severity_bin = six.text_type() for sev in media_severities: if sev in severity_sls: severity_bin += '1' else: severity_bin += '0' severity = six.text_type(int(severity_bin, 2)) medias_list.append({'active': active, 'mediatypeid': mediatypeid, 'period': period, 'sendto': sendto, 'severity': severity}) return medias_list user_exists = __salt__['zabbix.user_exists'](alias, **connection_args) if user_exists: user = __salt__['zabbix.user_get'](alias, **connection_args)[0] userid = user['userid'] update_usrgrps = False update_medias = False usergroups = __salt__['zabbix.usergroup_get'](userids=userid, **connection_args) cur_usrgrps = list() for usergroup in usergroups: cur_usrgrps.append(int(usergroup['usrgrpid'])) if set(cur_usrgrps) != set(usrgrps): update_usrgrps = True user_medias = __salt__['zabbix.user_getmedia'](userid, **connection_args) medias_formated = _media_format(medias) if user_medias: user_medias_copy = deepcopy(user_medias) for user_med in user_medias_copy: user_med.pop('userid') user_med.pop('mediaid') media_diff = [x for x in medias_formated if x not in user_medias_copy] + \ [y for y in user_medias_copy if y not in medias_formated] if media_diff: update_medias = True elif not user_medias and medias: update_medias = True # Dry run, test=true mode if __opts__['test']: if user_exists: if update_usrgrps or password_reset or update_medias: ret['result'] = None ret['comment'] = comment_user_updated else: ret['result'] = True ret['comment'] = comment_user_exists else: ret['result'] = None ret['comment'] = comment_user_created error = [] if user_exists: ret['result'] = True if update_usrgrps or password_reset or update_medias: ret['comment'] = comment_user_updated if update_usrgrps: __salt__['zabbix.user_update'](userid, usrgrps=usrgrps, **connection_args) updated_groups = __salt__['zabbix.usergroup_get'](userids=userid, **connection_args) cur_usrgrps = list() for usergroup in updated_groups: cur_usrgrps.append(int(usergroup['usrgrpid'])) usrgrp_diff = list(set(usrgrps) - set(cur_usrgrps)) if usrgrp_diff: error.append('Unable to update grpup(s): {0}'.format(usrgrp_diff)) ret['changes']['usrgrps'] = six.text_type(updated_groups) if password_reset: updated_password = __salt__['zabbix.user_update'](userid, passwd=passwd, **connection_args) if 'error' in updated_password: error.append(updated_groups['error']) else: ret['changes']['passwd'] = 'updated' if update_medias: for user_med in user_medias: deletedmed = __salt__['zabbix.user_deletemedia'](user_med['mediaid'], **connection_args) if 'error' in deletedmed: error.append(deletedmed['error']) for media in medias_formated: updatemed = __salt__['zabbix.user_addmedia'](userids=userid, active=media['active'], mediatypeid=media['mediatypeid'], period=media['period'], sendto=media['sendto'], severity=media['severity'], **connection_args) if 'error' in updatemed: error.append(updatemed['error']) ret['changes']['medias'] = six.text_type(medias_formated) else: ret['comment'] = comment_user_exists else: user_create = __salt__['zabbix.user_create'](alias, passwd, usrgrps, **kwargs) if 'error' not in user_create: ret['result'] = True ret['comment'] = comment_user_created ret['changes'] = changes_user_created else: ret['result'] = False ret['comment'] = comment_user_notcreated + six.text_type(user_create['error']) # error detected if error: ret['changes'] = {} ret['result'] = False ret['comment'] = six.text_type(error) return ret
[ "def", "present", "(", "alias", ",", "passwd", ",", "usrgrps", ",", "medias", "=", "None", ",", "password_reset", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "medias", "is", "None", ":", "medias", "=", "[", "]", "connection_args", "=", "{"...
Ensures that the user exists, eventually creates new user. NOTE: use argument firstname instead of name to not mess values with name from salt sls. .. versionadded:: 2016.3.0 :param alias: user alias :param passwd: user's password :param usrgrps: user groups to add the user to :param medias: Optional - user's medias to create :param password_reset: whether or not to reset password at update :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess \ with value supplied from Salt sls file. .. code-block:: yaml make_user: zabbix_user.present: - alias: George - passwd: donottellanyonE@456x - password_reset: True - usrgrps: - 13 - 7 - medias: - me@example.com: - mediatype: mail - period: '1-7,00:00-24:00' - severity: NIWAHD - make_jabber: - active: true - mediatype: jabber - period: '1-5,08:00-19:00' - sendto: jabbera@example.com - text_me_morning_disabled: - active: false - mediatype: sms - period: '1-5,09:30-10:00' - severity: D - sendto: '+42032132588568'
[ "Ensures", "that", "the", "user", "exists", "eventually", "creates", "new", "user", ".", "NOTE", ":", "use", "argument", "firstname", "instead", "of", "name", "to", "not", "mess", "values", "with", "name", "from", "salt", "sls", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_user.py#L121-L352
train
saltstack/salt
salt/states/zabbix_user.py
absent
def absent(name, **kwargs): ''' Ensures that the user does not exist, eventually delete user. .. versionadded:: 2016.3.0 :param name: user alias :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) .. code-block:: yaml George: zabbix_user.absent ''' connection_args = {} if '_connection_user' in kwargs: connection_args['_connection_user'] = kwargs['_connection_user'] if '_connection_password' in kwargs: connection_args['_connection_password'] = kwargs['_connection_password'] if '_connection_url' in kwargs: connection_args['_connection_url'] = kwargs['_connection_url'] ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Comment and change messages comment_user_deleted = 'USer {0} deleted.'.format(name) comment_user_notdeleted = 'Unable to delete user: {0}. '.format(name) comment_user_notexists = 'User {0} does not exist.'.format(name) changes_user_deleted = {name: {'old': 'User {0} exists.'.format(name), 'new': 'User {0} deleted.'.format(name), } } user_get = __salt__['zabbix.user_get'](name, **connection_args) # Dry run, test=true mode if __opts__['test']: if not user_get: ret['result'] = True ret['comment'] = comment_user_notexists else: ret['result'] = None ret['comment'] = comment_user_deleted ret['changes'] = changes_user_deleted if not user_get: ret['result'] = True ret['comment'] = comment_user_notexists else: try: userid = user_get[0]['userid'] user_delete = __salt__['zabbix.user_delete'](userid, **connection_args) except KeyError: user_delete = False if user_delete and 'error' not in user_delete: ret['result'] = True ret['comment'] = comment_user_deleted ret['changes'] = changes_user_deleted else: ret['result'] = False ret['comment'] = comment_user_notdeleted + six.text_type(user_delete['error']) return ret
python
def absent(name, **kwargs): ''' Ensures that the user does not exist, eventually delete user. .. versionadded:: 2016.3.0 :param name: user alias :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) .. code-block:: yaml George: zabbix_user.absent ''' connection_args = {} if '_connection_user' in kwargs: connection_args['_connection_user'] = kwargs['_connection_user'] if '_connection_password' in kwargs: connection_args['_connection_password'] = kwargs['_connection_password'] if '_connection_url' in kwargs: connection_args['_connection_url'] = kwargs['_connection_url'] ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Comment and change messages comment_user_deleted = 'USer {0} deleted.'.format(name) comment_user_notdeleted = 'Unable to delete user: {0}. '.format(name) comment_user_notexists = 'User {0} does not exist.'.format(name) changes_user_deleted = {name: {'old': 'User {0} exists.'.format(name), 'new': 'User {0} deleted.'.format(name), } } user_get = __salt__['zabbix.user_get'](name, **connection_args) # Dry run, test=true mode if __opts__['test']: if not user_get: ret['result'] = True ret['comment'] = comment_user_notexists else: ret['result'] = None ret['comment'] = comment_user_deleted ret['changes'] = changes_user_deleted if not user_get: ret['result'] = True ret['comment'] = comment_user_notexists else: try: userid = user_get[0]['userid'] user_delete = __salt__['zabbix.user_delete'](userid, **connection_args) except KeyError: user_delete = False if user_delete and 'error' not in user_delete: ret['result'] = True ret['comment'] = comment_user_deleted ret['changes'] = changes_user_deleted else: ret['result'] = False ret['comment'] = comment_user_notdeleted + six.text_type(user_delete['error']) return ret
[ "def", "absent", "(", "name", ",", "*", "*", "kwargs", ")", ":", "connection_args", "=", "{", "}", "if", "'_connection_user'", "in", "kwargs", ":", "connection_args", "[", "'_connection_user'", "]", "=", "kwargs", "[", "'_connection_user'", "]", "if", "'_con...
Ensures that the user does not exist, eventually delete user. .. versionadded:: 2016.3.0 :param name: user alias :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) .. code-block:: yaml George: zabbix_user.absent
[ "Ensures", "that", "the", "user", "does", "not", "exist", "eventually", "delete", "user", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_user.py#L355-L421
train
saltstack/salt
salt/utils/pushover.py
query
def query(function, token=None, api_version='1', method='POST', header_dict=None, data=None, query_params=None, opts=None): ''' PushOver object method function to construct and execute on the API URL. :param token: The PushOver api key. :param api_version: The PushOver API version to use, defaults to version 1. :param function: The PushOver api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. :return: The json response from the API call or False. ''' ret = {'message': '', 'res': True} pushover_functions = { 'message': { 'request': 'messages.json', 'response': 'status', }, 'validate_user': { 'request': 'users/validate.json', 'response': 'status', }, 'validate_sound': { 'request': 'sounds.json', 'response': 'status', }, } api_url = 'https://api.pushover.net' base_url = _urljoin(api_url, api_version + '/') path = pushover_functions.get(function).get('request') url = _urljoin(base_url, path, False) if not query_params: query_params = {} decode = True if method == 'DELETE': decode = False result = salt.utils.http.query( url, method, params=query_params, data=data, header_dict=header_dict, decode=decode, decode_type='json', text=True, status=True, cookies=True, persist_session=True, opts=opts, ) if result.get('status', None) == salt.ext.six.moves.http_client.OK: response = pushover_functions.get(function).get('response') if response in result and result[response] == 0: ret['res'] = False ret['message'] = result return ret else: try: if 'response' in result and result[response] == 0: ret['res'] = False ret['message'] = result except ValueError: ret['res'] = False ret['message'] = result return ret
python
def query(function, token=None, api_version='1', method='POST', header_dict=None, data=None, query_params=None, opts=None): ''' PushOver object method function to construct and execute on the API URL. :param token: The PushOver api key. :param api_version: The PushOver API version to use, defaults to version 1. :param function: The PushOver api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. :return: The json response from the API call or False. ''' ret = {'message': '', 'res': True} pushover_functions = { 'message': { 'request': 'messages.json', 'response': 'status', }, 'validate_user': { 'request': 'users/validate.json', 'response': 'status', }, 'validate_sound': { 'request': 'sounds.json', 'response': 'status', }, } api_url = 'https://api.pushover.net' base_url = _urljoin(api_url, api_version + '/') path = pushover_functions.get(function).get('request') url = _urljoin(base_url, path, False) if not query_params: query_params = {} decode = True if method == 'DELETE': decode = False result = salt.utils.http.query( url, method, params=query_params, data=data, header_dict=header_dict, decode=decode, decode_type='json', text=True, status=True, cookies=True, persist_session=True, opts=opts, ) if result.get('status', None) == salt.ext.six.moves.http_client.OK: response = pushover_functions.get(function).get('response') if response in result and result[response] == 0: ret['res'] = False ret['message'] = result return ret else: try: if 'response' in result and result[response] == 0: ret['res'] = False ret['message'] = result except ValueError: ret['res'] = False ret['message'] = result return ret
[ "def", "query", "(", "function", ",", "token", "=", "None", ",", "api_version", "=", "'1'", ",", "method", "=", "'POST'", ",", "header_dict", "=", "None", ",", "data", "=", "None", ",", "query_params", "=", "None", ",", "opts", "=", "None", ")", ":",...
PushOver object method function to construct and execute on the API URL. :param token: The PushOver api key. :param api_version: The PushOver API version to use, defaults to version 1. :param function: The PushOver api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. :return: The json response from the API call or False.
[ "PushOver", "object", "method", "function", "to", "construct", "and", "execute", "on", "the", "API", "URL", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pushover.py#L32-L110
train
saltstack/salt
salt/utils/pushover.py
validate_sound
def validate_sound(sound, token): ''' Send a message to a Pushover user or group. :param sound: The sound that we want to verify :param token: The PushOver token. ''' ret = { 'message': 'Sound is invalid', 'res': False } parameters = dict() parameters['token'] = token response = query(function='validate_sound', method='GET', query_params=parameters) if response['res']: if 'message' in response: _message = response.get('message', '') if 'status' in _message: if _message.get('dict', {}).get('status', '') == 1: sounds = _message.get('dict', {}).get('sounds', '') if sound in sounds: ret['message'] = 'Valid sound {0}.'.format(sound) ret['res'] = True else: ret['message'] = 'Warning: {0} not a valid sound.'.format(sound) ret['res'] = False else: ret['message'] = ''.join(_message.get('dict', {}).get('errors')) return ret
python
def validate_sound(sound, token): ''' Send a message to a Pushover user or group. :param sound: The sound that we want to verify :param token: The PushOver token. ''' ret = { 'message': 'Sound is invalid', 'res': False } parameters = dict() parameters['token'] = token response = query(function='validate_sound', method='GET', query_params=parameters) if response['res']: if 'message' in response: _message = response.get('message', '') if 'status' in _message: if _message.get('dict', {}).get('status', '') == 1: sounds = _message.get('dict', {}).get('sounds', '') if sound in sounds: ret['message'] = 'Valid sound {0}.'.format(sound) ret['res'] = True else: ret['message'] = 'Warning: {0} not a valid sound.'.format(sound) ret['res'] = False else: ret['message'] = ''.join(_message.get('dict', {}).get('errors')) return ret
[ "def", "validate_sound", "(", "sound", ",", "token", ")", ":", "ret", "=", "{", "'message'", ":", "'Sound is invalid'", ",", "'res'", ":", "False", "}", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "response", "="...
Send a message to a Pushover user or group. :param sound: The sound that we want to verify :param token: The PushOver token.
[ "Send", "a", "message", "to", "a", "Pushover", "user", "or", "group", ".", ":", "param", "sound", ":", "The", "sound", "that", "we", "want", "to", "verify", ":", "param", "token", ":", "The", "PushOver", "token", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pushover.py#L113-L145
train
saltstack/salt
salt/utils/pushover.py
validate_user
def validate_user(user, device, token): ''' Send a message to a Pushover user or group. :param user: The user or group name, either will work. :param device: The device for the user. :param token: The PushOver token. ''' res = { 'message': 'User key is invalid', 'result': False } parameters = dict() parameters['user'] = user parameters['token'] = token if device: parameters['device'] = device response = query(function='validate_user', method='POST', header_dict={'Content-Type': 'application/x-www-form-urlencoded'}, data=_urlencode(parameters)) if response['res']: if 'message' in response: _message = response.get('message', '') if 'status' in _message: if _message.get('dict', {}).get('status', None) == 1: res['result'] = True res['message'] = 'User key is valid.' else: res['result'] = False res['message'] = ''.join(_message.get('dict', {}).get('errors')) return res
python
def validate_user(user, device, token): ''' Send a message to a Pushover user or group. :param user: The user or group name, either will work. :param device: The device for the user. :param token: The PushOver token. ''' res = { 'message': 'User key is invalid', 'result': False } parameters = dict() parameters['user'] = user parameters['token'] = token if device: parameters['device'] = device response = query(function='validate_user', method='POST', header_dict={'Content-Type': 'application/x-www-form-urlencoded'}, data=_urlencode(parameters)) if response['res']: if 'message' in response: _message = response.get('message', '') if 'status' in _message: if _message.get('dict', {}).get('status', None) == 1: res['result'] = True res['message'] = 'User key is valid.' else: res['result'] = False res['message'] = ''.join(_message.get('dict', {}).get('errors')) return res
[ "def", "validate_user", "(", "user", ",", "device", ",", "token", ")", ":", "res", "=", "{", "'message'", ":", "'User key is invalid'", ",", "'result'", ":", "False", "}", "parameters", "=", "dict", "(", ")", "parameters", "[", "'user'", "]", "=", "user"...
Send a message to a Pushover user or group. :param user: The user or group name, either will work. :param device: The device for the user. :param token: The PushOver token.
[ "Send", "a", "message", "to", "a", "Pushover", "user", "or", "group", ".", ":", "param", "user", ":", "The", "user", "or", "group", "name", "either", "will", "work", ".", ":", "param", "device", ":", "The", "device", "for", "the", "user", ".", ":", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pushover.py#L148-L183
train
saltstack/salt
salt/modules/inspectlib/collector.py
is_alive
def is_alive(pidfile): ''' Check if PID is still alive. ''' try: with salt.utils.files.fopen(pidfile) as fp_: os.kill(int(fp_.read().strip()), 0) return True except Exception as ex: if os.access(pidfile, os.W_OK) and os.path.isfile(pidfile): os.unlink(pidfile) return False
python
def is_alive(pidfile): ''' Check if PID is still alive. ''' try: with salt.utils.files.fopen(pidfile) as fp_: os.kill(int(fp_.read().strip()), 0) return True except Exception as ex: if os.access(pidfile, os.W_OK) and os.path.isfile(pidfile): os.unlink(pidfile) return False
[ "def", "is_alive", "(", "pidfile", ")", ":", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "pidfile", ")", "as", "fp_", ":", "os", ".", "kill", "(", "int", "(", "fp_", ".", "read", "(", ")", ".", "strip", "(", ")", ...
Check if PID is still alive.
[ "Check", "if", "PID", "is", "still", "alive", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L475-L486
train
saltstack/salt
salt/modules/inspectlib/collector.py
main
def main(dbfile, pidfile, mode): ''' Main analyzer routine. ''' Inspector(dbfile, pidfile).reuse_snapshot().snapshot(mode)
python
def main(dbfile, pidfile, mode): ''' Main analyzer routine. ''' Inspector(dbfile, pidfile).reuse_snapshot().snapshot(mode)
[ "def", "main", "(", "dbfile", ",", "pidfile", ",", "mode", ")", ":", "Inspector", "(", "dbfile", ",", "pidfile", ")", ".", "reuse_snapshot", "(", ")", ".", "snapshot", "(", "mode", ")" ]
Main analyzer routine.
[ "Main", "analyzer", "routine", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L489-L493
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._syscall
def _syscall(self, command, input=None, env=None, *params): ''' Call an external system command. ''' return Popen([command] + list(params), stdout=PIPE, stdin=PIPE, stderr=STDOUT, env=env or os.environ).communicate(input=input)
python
def _syscall(self, command, input=None, env=None, *params): ''' Call an external system command. ''' return Popen([command] + list(params), stdout=PIPE, stdin=PIPE, stderr=STDOUT, env=env or os.environ).communicate(input=input)
[ "def", "_syscall", "(", "self", ",", "command", ",", "input", "=", "None", ",", "env", "=", "None", ",", "*", "params", ")", ":", "return", "Popen", "(", "[", "command", "]", "+", "list", "(", "params", ")", ",", "stdout", "=", "PIPE", ",", "stdi...
Call an external system command.
[ "Call", "an", "external", "system", "command", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L77-L82
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._get_cfg_pkgs
def _get_cfg_pkgs(self): ''' Package scanner switcher between the platforms. :return: ''' if self.grains_core.os_data().get('os_family') == 'Debian': return self.__get_cfg_pkgs_dpkg() elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']: return self.__get_cfg_pkgs_rpm() else: return dict()
python
def _get_cfg_pkgs(self): ''' Package scanner switcher between the platforms. :return: ''' if self.grains_core.os_data().get('os_family') == 'Debian': return self.__get_cfg_pkgs_dpkg() elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']: return self.__get_cfg_pkgs_rpm() else: return dict()
[ "def", "_get_cfg_pkgs", "(", "self", ")", ":", "if", "self", ".", "grains_core", ".", "os_data", "(", ")", ".", "get", "(", "'os_family'", ")", "==", "'Debian'", ":", "return", "self", ".", "__get_cfg_pkgs_dpkg", "(", ")", "elif", "self", ".", "grains_co...
Package scanner switcher between the platforms. :return:
[ "Package", "scanner", "switcher", "between", "the", "platforms", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L84-L95
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector.__get_cfg_pkgs_dpkg
def __get_cfg_pkgs_dpkg(self): ''' Get packages with configuration files on Dpkg systems. :return: ''' # Get list of all available packages data = dict() for pkg_name in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None, '-Wf', "${binary:Package}\\n")[0]).split(os.linesep): pkg_name = pkg_name.strip() if not pkg_name: continue data[pkg_name] = list() for pkg_cfg_item in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None, '-Wf', "${Conffiles}\\n", pkg_name)[0]).split(os.linesep): pkg_cfg_item = pkg_cfg_item.strip() if not pkg_cfg_item: continue pkg_cfg_file, pkg_cfg_sum = pkg_cfg_item.strip().split(" ", 1) data[pkg_name].append(pkg_cfg_file) # Dpkg meta data is unreliable. Check every package # and remove which actually does not have config files. if not data[pkg_name]: data.pop(pkg_name) return data
python
def __get_cfg_pkgs_dpkg(self): ''' Get packages with configuration files on Dpkg systems. :return: ''' # Get list of all available packages data = dict() for pkg_name in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None, '-Wf', "${binary:Package}\\n")[0]).split(os.linesep): pkg_name = pkg_name.strip() if not pkg_name: continue data[pkg_name] = list() for pkg_cfg_item in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None, '-Wf', "${Conffiles}\\n", pkg_name)[0]).split(os.linesep): pkg_cfg_item = pkg_cfg_item.strip() if not pkg_cfg_item: continue pkg_cfg_file, pkg_cfg_sum = pkg_cfg_item.strip().split(" ", 1) data[pkg_name].append(pkg_cfg_file) # Dpkg meta data is unreliable. Check every package # and remove which actually does not have config files. if not data[pkg_name]: data.pop(pkg_name) return data
[ "def", "__get_cfg_pkgs_dpkg", "(", "self", ")", ":", "# Get list of all available packages", "data", "=", "dict", "(", ")", "for", "pkg_name", "in", "salt", ".", "utils", ".", "stringutils", ".", "to_str", "(", "self", ".", "_syscall", "(", "'dpkg-query'", ","...
Get packages with configuration files on Dpkg systems. :return:
[ "Get", "packages", "with", "configuration", "files", "on", "Dpkg", "systems", ".", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L97-L124
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector.__get_cfg_pkgs_rpm
def __get_cfg_pkgs_rpm(self): ''' Get packages with configuration files on RPM systems. ''' out, err = self._syscall('rpm', None, None, '-qa', '--configfiles', '--queryformat', '%{name}-%{version}-%{release}\\n') data = dict() pkg_name = None pkg_configs = [] out = salt.utils.stringutils.to_str(out) for line in out.split(os.linesep): line = line.strip() if not line: continue if not line.startswith("/"): if pkg_name and pkg_configs: data[pkg_name] = pkg_configs pkg_name = line pkg_configs = [] else: pkg_configs.append(line) if pkg_name and pkg_configs: data[pkg_name] = pkg_configs return data
python
def __get_cfg_pkgs_rpm(self): ''' Get packages with configuration files on RPM systems. ''' out, err = self._syscall('rpm', None, None, '-qa', '--configfiles', '--queryformat', '%{name}-%{version}-%{release}\\n') data = dict() pkg_name = None pkg_configs = [] out = salt.utils.stringutils.to_str(out) for line in out.split(os.linesep): line = line.strip() if not line: continue if not line.startswith("/"): if pkg_name and pkg_configs: data[pkg_name] = pkg_configs pkg_name = line pkg_configs = [] else: pkg_configs.append(line) if pkg_name and pkg_configs: data[pkg_name] = pkg_configs return data
[ "def", "__get_cfg_pkgs_rpm", "(", "self", ")", ":", "out", ",", "err", "=", "self", ".", "_syscall", "(", "'rpm'", ",", "None", ",", "None", ",", "'-qa'", ",", "'--configfiles'", ",", "'--queryformat'", ",", "'%{name}-%{version}-%{release}\\\\n'", ")", "data",...
Get packages with configuration files on RPM systems.
[ "Get", "packages", "with", "configuration", "files", "on", "RPM", "systems", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L126-L152
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._get_changed_cfg_pkgs
def _get_changed_cfg_pkgs(self, data): ''' Filter out unchanged packages on the Debian or RPM systems. :param data: Structure {package-name -> [ file .. file1 ]} :return: Same structure as data, except only files that were changed. ''' f_data = dict() for pkg_name, pkg_files in data.items(): cfgs = list() cfg_data = list() if self.grains_core.os_data().get('os_family') == 'Debian': cfg_data = salt.utils.stringutils.to_str(self._syscall("dpkg", None, None, '--verify', pkg_name)[0]).split(os.linesep) elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']: cfg_data = salt.utils.stringutils.to_str(self._syscall("rpm", None, None, '-V', '--nodeps', '--nodigest', '--nosignature', '--nomtime', '--nolinkto', pkg_name)[0]).split(os.linesep) for line in cfg_data: line = line.strip() if not line or line.find(" c ") < 0 or line.split(" ")[0].find("5") < 0: continue cfg_file = line.split(" ")[-1] if cfg_file in pkg_files: cfgs.append(cfg_file) if cfgs: f_data[pkg_name] = cfgs return f_data
python
def _get_changed_cfg_pkgs(self, data): ''' Filter out unchanged packages on the Debian or RPM systems. :param data: Structure {package-name -> [ file .. file1 ]} :return: Same structure as data, except only files that were changed. ''' f_data = dict() for pkg_name, pkg_files in data.items(): cfgs = list() cfg_data = list() if self.grains_core.os_data().get('os_family') == 'Debian': cfg_data = salt.utils.stringutils.to_str(self._syscall("dpkg", None, None, '--verify', pkg_name)[0]).split(os.linesep) elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']: cfg_data = salt.utils.stringutils.to_str(self._syscall("rpm", None, None, '-V', '--nodeps', '--nodigest', '--nosignature', '--nomtime', '--nolinkto', pkg_name)[0]).split(os.linesep) for line in cfg_data: line = line.strip() if not line or line.find(" c ") < 0 or line.split(" ")[0].find("5") < 0: continue cfg_file = line.split(" ")[-1] if cfg_file in pkg_files: cfgs.append(cfg_file) if cfgs: f_data[pkg_name] = cfgs return f_data
[ "def", "_get_changed_cfg_pkgs", "(", "self", ",", "data", ")", ":", "f_data", "=", "dict", "(", ")", "for", "pkg_name", ",", "pkg_files", "in", "data", ".", "items", "(", ")", ":", "cfgs", "=", "list", "(", ")", "cfg_data", "=", "list", "(", ")", "...
Filter out unchanged packages on the Debian or RPM systems. :param data: Structure {package-name -> [ file .. file1 ]} :return: Same structure as data, except only files that were changed.
[ "Filter", "out", "unchanged", "packages", "on", "the", "Debian", "or", "RPM", "systems", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L154-L182
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._save_cfg_packages
def _save_cfg_packages(self, data): ''' Save configuration packages. (NG) :param data: :return: ''' pkg_id = 0 pkg_cfg_id = 0 for pkg_name, pkg_configs in data.items(): pkg = Package() pkg.id = pkg_id pkg.name = pkg_name self.db.store(pkg) for pkg_config in pkg_configs: cfg = PackageCfgFile() cfg.id = pkg_cfg_id cfg.pkgid = pkg_id cfg.path = pkg_config self.db.store(cfg) pkg_cfg_id += 1 pkg_id += 1
python
def _save_cfg_packages(self, data): ''' Save configuration packages. (NG) :param data: :return: ''' pkg_id = 0 pkg_cfg_id = 0 for pkg_name, pkg_configs in data.items(): pkg = Package() pkg.id = pkg_id pkg.name = pkg_name self.db.store(pkg) for pkg_config in pkg_configs: cfg = PackageCfgFile() cfg.id = pkg_cfg_id cfg.pkgid = pkg_id cfg.path = pkg_config self.db.store(cfg) pkg_cfg_id += 1 pkg_id += 1
[ "def", "_save_cfg_packages", "(", "self", ",", "data", ")", ":", "pkg_id", "=", "0", "pkg_cfg_id", "=", "0", "for", "pkg_name", ",", "pkg_configs", "in", "data", ".", "items", "(", ")", ":", "pkg", "=", "Package", "(", ")", "pkg", ".", "id", "=", "...
Save configuration packages. (NG) :param data: :return:
[ "Save", "configuration", "packages", ".", "(", "NG", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L184-L207
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._save_payload
def _save_payload(self, files, directories, links): ''' Save payload (unmanaged files) :param files: :param directories: :param links: :return: ''' idx = 0 for p_type, p_list in (('f', files), ('d', directories), ('l', links,),): for p_obj in p_list: stats = os.stat(p_obj) payload = PayloadFile() payload.id = idx payload.path = p_obj payload.p_type = p_type payload.mode = stats.st_mode payload.uid = stats.st_uid payload.gid = stats.st_gid payload.p_size = stats.st_size payload.atime = stats.st_atime payload.mtime = stats.st_mtime payload.ctime = stats.st_ctime idx += 1 self.db.store(payload)
python
def _save_payload(self, files, directories, links): ''' Save payload (unmanaged files) :param files: :param directories: :param links: :return: ''' idx = 0 for p_type, p_list in (('f', files), ('d', directories), ('l', links,),): for p_obj in p_list: stats = os.stat(p_obj) payload = PayloadFile() payload.id = idx payload.path = p_obj payload.p_type = p_type payload.mode = stats.st_mode payload.uid = stats.st_uid payload.gid = stats.st_gid payload.p_size = stats.st_size payload.atime = stats.st_atime payload.mtime = stats.st_mtime payload.ctime = stats.st_ctime idx += 1 self.db.store(payload)
[ "def", "_save_payload", "(", "self", ",", "files", ",", "directories", ",", "links", ")", ":", "idx", "=", "0", "for", "p_type", ",", "p_list", "in", "(", "(", "'f'", ",", "files", ")", ",", "(", "'d'", ",", "directories", ")", ",", "(", "'l'", "...
Save payload (unmanaged files) :param files: :param directories: :param links: :return:
[ "Save", "payload", "(", "unmanaged", "files", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L209-L237
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._get_managed_files
def _get_managed_files(self): ''' Build a in-memory data of all managed files. ''' if self.grains_core.os_data().get('os_family') == 'Debian': return self.__get_managed_files_dpkg() elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']: return self.__get_managed_files_rpm() return list(), list(), list()
python
def _get_managed_files(self): ''' Build a in-memory data of all managed files. ''' if self.grains_core.os_data().get('os_family') == 'Debian': return self.__get_managed_files_dpkg() elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']: return self.__get_managed_files_rpm() return list(), list(), list()
[ "def", "_get_managed_files", "(", "self", ")", ":", "if", "self", ".", "grains_core", ".", "os_data", "(", ")", ".", "get", "(", "'os_family'", ")", "==", "'Debian'", ":", "return", "self", ".", "__get_managed_files_dpkg", "(", ")", "elif", "self", ".", ...
Build a in-memory data of all managed files.
[ "Build", "a", "in", "-", "memory", "data", "of", "all", "managed", "files", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L239-L248
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector.__get_managed_files_dpkg
def __get_managed_files_dpkg(self): ''' Get a list of all system files, belonging to the Debian package manager. ''' dirs = set() links = set() files = set() for pkg_name in salt.utils.stringutils.to_str(self._syscall("dpkg-query", None, None, '-Wf', '${binary:Package}\\n')[0]).split(os.linesep): pkg_name = pkg_name.strip() if not pkg_name: continue for resource in salt.utils.stringutils.to_str(self._syscall("dpkg", None, None, '-L', pkg_name)[0]).split(os.linesep): resource = resource.strip() if not resource or resource in ['/', './', '.']: continue if os.path.isdir(resource): dirs.add(resource) elif os.path.islink(resource): links.add(resource) elif os.path.isfile(resource): files.add(resource) return sorted(files), sorted(dirs), sorted(links)
python
def __get_managed_files_dpkg(self): ''' Get a list of all system files, belonging to the Debian package manager. ''' dirs = set() links = set() files = set() for pkg_name in salt.utils.stringutils.to_str(self._syscall("dpkg-query", None, None, '-Wf', '${binary:Package}\\n')[0]).split(os.linesep): pkg_name = pkg_name.strip() if not pkg_name: continue for resource in salt.utils.stringutils.to_str(self._syscall("dpkg", None, None, '-L', pkg_name)[0]).split(os.linesep): resource = resource.strip() if not resource or resource in ['/', './', '.']: continue if os.path.isdir(resource): dirs.add(resource) elif os.path.islink(resource): links.add(resource) elif os.path.isfile(resource): files.add(resource) return sorted(files), sorted(dirs), sorted(links)
[ "def", "__get_managed_files_dpkg", "(", "self", ")", ":", "dirs", "=", "set", "(", ")", "links", "=", "set", "(", ")", "files", "=", "set", "(", ")", "for", "pkg_name", "in", "salt", ".", "utils", ".", "stringutils", ".", "to_str", "(", "self", ".", ...
Get a list of all system files, belonging to the Debian package manager.
[ "Get", "a", "list", "of", "all", "system", "files", "belonging", "to", "the", "Debian", "package", "manager", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L250-L274
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector.__get_managed_files_rpm
def __get_managed_files_rpm(self): ''' Get a list of all system files, belonging to the RedHat package manager. ''' dirs = set() links = set() files = set() for line in salt.utils.stringutils.to_str(self._syscall("rpm", None, None, '-qlav')[0]).split(os.linesep): line = line.strip() if not line: continue line = line.replace("\t", " ").split(" ") if line[0][0] == "d": dirs.add(line[-1]) elif line[0][0] == "l": links.add(line[-1]) elif line[0][0] == "-": files.add(line[-1]) return sorted(files), sorted(dirs), sorted(links)
python
def __get_managed_files_rpm(self): ''' Get a list of all system files, belonging to the RedHat package manager. ''' dirs = set() links = set() files = set() for line in salt.utils.stringutils.to_str(self._syscall("rpm", None, None, '-qlav')[0]).split(os.linesep): line = line.strip() if not line: continue line = line.replace("\t", " ").split(" ") if line[0][0] == "d": dirs.add(line[-1]) elif line[0][0] == "l": links.add(line[-1]) elif line[0][0] == "-": files.add(line[-1]) return sorted(files), sorted(dirs), sorted(links)
[ "def", "__get_managed_files_rpm", "(", "self", ")", ":", "dirs", "=", "set", "(", ")", "links", "=", "set", "(", ")", "files", "=", "set", "(", ")", "for", "line", "in", "salt", ".", "utils", ".", "stringutils", ".", "to_str", "(", "self", ".", "_s...
Get a list of all system files, belonging to the RedHat package manager.
[ "Get", "a", "list", "of", "all", "system", "files", "belonging", "to", "the", "RedHat", "package", "manager", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L276-L296
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._get_all_files
def _get_all_files(self, path, *exclude): ''' Walk implementation. Version in python 2.x and 3.x works differently. ''' files = list() dirs = list() links = list() if os.access(path, os.R_OK): for obj in os.listdir(path): obj = os.path.join(path, obj) valid = True for ex_obj in exclude: if obj.startswith(str(ex_obj)): valid = False continue if not valid or not os.path.exists(obj) or not os.access(obj, os.R_OK): continue if salt.utils.path.islink(obj): links.append(obj) elif os.path.isdir(obj): dirs.append(obj) f_obj, d_obj, l_obj = self._get_all_files(obj, *exclude) files.extend(f_obj) dirs.extend(d_obj) links.extend(l_obj) elif os.path.isfile(obj): files.append(obj) return sorted(files), sorted(dirs), sorted(links)
python
def _get_all_files(self, path, *exclude): ''' Walk implementation. Version in python 2.x and 3.x works differently. ''' files = list() dirs = list() links = list() if os.access(path, os.R_OK): for obj in os.listdir(path): obj = os.path.join(path, obj) valid = True for ex_obj in exclude: if obj.startswith(str(ex_obj)): valid = False continue if not valid or not os.path.exists(obj) or not os.access(obj, os.R_OK): continue if salt.utils.path.islink(obj): links.append(obj) elif os.path.isdir(obj): dirs.append(obj) f_obj, d_obj, l_obj = self._get_all_files(obj, *exclude) files.extend(f_obj) dirs.extend(d_obj) links.extend(l_obj) elif os.path.isfile(obj): files.append(obj) return sorted(files), sorted(dirs), sorted(links)
[ "def", "_get_all_files", "(", "self", ",", "path", ",", "*", "exclude", ")", ":", "files", "=", "list", "(", ")", "dirs", "=", "list", "(", ")", "links", "=", "list", "(", ")", "if", "os", ".", "access", "(", "path", ",", "os", ".", "R_OK", ")"...
Walk implementation. Version in python 2.x and 3.x works differently.
[ "Walk", "implementation", ".", "Version", "in", "python", "2", ".", "x", "and", "3", ".", "x", "works", "differently", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L298-L327
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._get_unmanaged_files
def _get_unmanaged_files(self, managed, system_all): ''' Get the intersection between all files and managed files. ''' m_files, m_dirs, m_links = managed s_files, s_dirs, s_links = system_all return (sorted(list(set(s_files).difference(m_files))), sorted(list(set(s_dirs).difference(m_dirs))), sorted(list(set(s_links).difference(m_links))))
python
def _get_unmanaged_files(self, managed, system_all): ''' Get the intersection between all files and managed files. ''' m_files, m_dirs, m_links = managed s_files, s_dirs, s_links = system_all return (sorted(list(set(s_files).difference(m_files))), sorted(list(set(s_dirs).difference(m_dirs))), sorted(list(set(s_links).difference(m_links))))
[ "def", "_get_unmanaged_files", "(", "self", ",", "managed", ",", "system_all", ")", ":", "m_files", ",", "m_dirs", ",", "m_links", "=", "managed", "s_files", ",", "s_dirs", ",", "s_links", "=", "system_all", "return", "(", "sorted", "(", "list", "(", "set"...
Get the intersection between all files and managed files.
[ "Get", "the", "intersection", "between", "all", "files", "and", "managed", "files", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L329-L338
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._scan_payload
def _scan_payload(self): ''' Scan the system. ''' # Get ignored points allowed = list() for allowed_dir in self.db.get(AllowedDir): if os.path.exists(allowed_dir.path): allowed.append(allowed_dir.path) ignored = list() if not allowed: for ignored_dir in self.db.get(IgnoredDir): if os.path.exists(ignored_dir.path): ignored.append(ignored_dir.path) all_files = list() all_dirs = list() all_links = list() for entry_path in [pth for pth in (allowed or os.listdir("/")) if pth]: if entry_path[0] != "/": entry_path = "/{0}".format(entry_path) if entry_path in ignored or os.path.islink(entry_path): continue e_files, e_dirs, e_links = self._get_all_files(entry_path, *ignored) all_files.extend(e_files) all_dirs.extend(e_dirs) all_links.extend(e_links) return self._get_unmanaged_files(self._get_managed_files(), (all_files, all_dirs, all_links,))
python
def _scan_payload(self): ''' Scan the system. ''' # Get ignored points allowed = list() for allowed_dir in self.db.get(AllowedDir): if os.path.exists(allowed_dir.path): allowed.append(allowed_dir.path) ignored = list() if not allowed: for ignored_dir in self.db.get(IgnoredDir): if os.path.exists(ignored_dir.path): ignored.append(ignored_dir.path) all_files = list() all_dirs = list() all_links = list() for entry_path in [pth for pth in (allowed or os.listdir("/")) if pth]: if entry_path[0] != "/": entry_path = "/{0}".format(entry_path) if entry_path in ignored or os.path.islink(entry_path): continue e_files, e_dirs, e_links = self._get_all_files(entry_path, *ignored) all_files.extend(e_files) all_dirs.extend(e_dirs) all_links.extend(e_links) return self._get_unmanaged_files(self._get_managed_files(), (all_files, all_dirs, all_links,))
[ "def", "_scan_payload", "(", "self", ")", ":", "# Get ignored points", "allowed", "=", "list", "(", ")", "for", "allowed_dir", "in", "self", ".", "db", ".", "get", "(", "AllowedDir", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "allowed_dir", ...
Scan the system.
[ "Scan", "the", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L340-L369
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._prepare_full_scan
def _prepare_full_scan(self, **kwargs): ''' Prepare full system scan by setting up the database etc. ''' self.db.open(new=True) # Add ignored filesystems ignored_fs = set() ignored_fs |= set(self.IGNORE_PATHS) mounts = salt.utils.fsutils._get_mounts() for device, data in mounts.items(): if device in self.IGNORE_MOUNTS: for mpt in data: ignored_fs.add(mpt['mount_point']) continue for mpt in data: if mpt['type'] in self.IGNORE_FS_TYPES: ignored_fs.add(mpt['mount_point']) # Remove leafs of ignored filesystems ignored_all = list() for entry in sorted(list(ignored_fs)): valid = True for e_entry in ignored_all: if entry.startswith(e_entry): valid = False break if valid: ignored_all.append(entry) # Save to the database for further scan for ignored_dir in ignored_all: dir_obj = IgnoredDir() dir_obj.path = ignored_dir self.db.store(dir_obj) # Add allowed filesystems (overrides all above at full scan) allowed = [elm for elm in kwargs.get("filter", "").split(",") if elm] for allowed_dir in allowed: dir_obj = AllowedDir() dir_obj.path = allowed_dir self.db.store(dir_obj) return ignored_all
python
def _prepare_full_scan(self, **kwargs): ''' Prepare full system scan by setting up the database etc. ''' self.db.open(new=True) # Add ignored filesystems ignored_fs = set() ignored_fs |= set(self.IGNORE_PATHS) mounts = salt.utils.fsutils._get_mounts() for device, data in mounts.items(): if device in self.IGNORE_MOUNTS: for mpt in data: ignored_fs.add(mpt['mount_point']) continue for mpt in data: if mpt['type'] in self.IGNORE_FS_TYPES: ignored_fs.add(mpt['mount_point']) # Remove leafs of ignored filesystems ignored_all = list() for entry in sorted(list(ignored_fs)): valid = True for e_entry in ignored_all: if entry.startswith(e_entry): valid = False break if valid: ignored_all.append(entry) # Save to the database for further scan for ignored_dir in ignored_all: dir_obj = IgnoredDir() dir_obj.path = ignored_dir self.db.store(dir_obj) # Add allowed filesystems (overrides all above at full scan) allowed = [elm for elm in kwargs.get("filter", "").split(",") if elm] for allowed_dir in allowed: dir_obj = AllowedDir() dir_obj.path = allowed_dir self.db.store(dir_obj) return ignored_all
[ "def", "_prepare_full_scan", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "db", ".", "open", "(", "new", "=", "True", ")", "# Add ignored filesystems", "ignored_fs", "=", "set", "(", ")", "ignored_fs", "|=", "set", "(", "self", ".", "IG...
Prepare full system scan by setting up the database etc.
[ "Prepare", "full", "system", "scan", "by", "setting", "up", "the", "database", "etc", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L371-L412
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector._init_env
def _init_env(self): ''' Initialize some Salt environment. ''' from salt.config import minion_config from salt.grains import core as g_core g_core.__opts__ = minion_config(self.DEFAULT_MINION_CONFIG_PATH) self.grains_core = g_core
python
def _init_env(self): ''' Initialize some Salt environment. ''' from salt.config import minion_config from salt.grains import core as g_core g_core.__opts__ = minion_config(self.DEFAULT_MINION_CONFIG_PATH) self.grains_core = g_core
[ "def", "_init_env", "(", "self", ")", ":", "from", "salt", ".", "config", "import", "minion_config", "from", "salt", ".", "grains", "import", "core", "as", "g_core", "g_core", ".", "__opts__", "=", "minion_config", "(", "self", ".", "DEFAULT_MINION_CONFIG_PATH...
Initialize some Salt environment.
[ "Initialize", "some", "Salt", "environment", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L414-L421
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector.snapshot
def snapshot(self, mode): ''' Take a snapshot of the system. ''' self._init_env() self._save_cfg_packages(self._get_changed_cfg_pkgs(self._get_cfg_pkgs())) self._save_payload(*self._scan_payload())
python
def snapshot(self, mode): ''' Take a snapshot of the system. ''' self._init_env() self._save_cfg_packages(self._get_changed_cfg_pkgs(self._get_cfg_pkgs())) self._save_payload(*self._scan_payload())
[ "def", "snapshot", "(", "self", ",", "mode", ")", ":", "self", ".", "_init_env", "(", ")", "self", ".", "_save_cfg_packages", "(", "self", ".", "_get_changed_cfg_pkgs", "(", "self", ".", "_get_cfg_pkgs", "(", ")", ")", ")", "self", ".", "_save_payload", ...
Take a snapshot of the system.
[ "Take", "a", "snapshot", "of", "the", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L423-L430
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector.request_snapshot
def request_snapshot(self, mode, priority=19, **kwargs): ''' Take a snapshot of the system. ''' if mode not in self.MODE: raise InspectorSnapshotException("Unknown mode: '{0}'".format(mode)) if is_alive(self.pidfile): raise CommandExecutionError('Inspection already in progress.') self._prepare_full_scan(**kwargs) os.system("nice -{0} python {1} {2} {3} {4} & > /dev/null".format( priority, __file__, os.path.dirname(self.pidfile), os.path.dirname(self.dbfile), mode))
python
def request_snapshot(self, mode, priority=19, **kwargs): ''' Take a snapshot of the system. ''' if mode not in self.MODE: raise InspectorSnapshotException("Unknown mode: '{0}'".format(mode)) if is_alive(self.pidfile): raise CommandExecutionError('Inspection already in progress.') self._prepare_full_scan(**kwargs) os.system("nice -{0} python {1} {2} {3} {4} & > /dev/null".format( priority, __file__, os.path.dirname(self.pidfile), os.path.dirname(self.dbfile), mode))
[ "def", "request_snapshot", "(", "self", ",", "mode", ",", "priority", "=", "19", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "not", "in", "self", ".", "MODE", ":", "raise", "InspectorSnapshotException", "(", "\"Unknown mode: '{0}'\"", ".", "format", "...
Take a snapshot of the system.
[ "Take", "a", "snapshot", "of", "the", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L432-L445
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector.export
def export(self, description, local=False, path='/tmp', format='qcow2'): ''' Export description for Kiwi. :param local: :param path: :return: ''' kiwiproc.__salt__ = __salt__ return kiwiproc.KiwiExporter(grains=__grains__, format=format).load(**description).export('something')
python
def export(self, description, local=False, path='/tmp', format='qcow2'): ''' Export description for Kiwi. :param local: :param path: :return: ''' kiwiproc.__salt__ = __salt__ return kiwiproc.KiwiExporter(grains=__grains__, format=format).load(**description).export('something')
[ "def", "export", "(", "self", ",", "description", ",", "local", "=", "False", ",", "path", "=", "'/tmp'", ",", "format", "=", "'qcow2'", ")", ":", "kiwiproc", ".", "__salt__", "=", "__salt__", "return", "kiwiproc", ".", "KiwiExporter", "(", "grains", "="...
Export description for Kiwi. :param local: :param path: :return:
[ "Export", "description", "for", "Kiwi", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L447-L457
train
saltstack/salt
salt/modules/inspectlib/collector.py
Inspector.build
def build(self, format='qcow2', path='/tmp'): ''' Build an image using Kiwi. :param format: :param path: :return: ''' if kiwi is None: msg = 'Unable to build the image due to the missing dependencies: Kiwi module is not available.' log.error(msg) raise CommandExecutionError(msg) raise CommandExecutionError("Build is not yet implemented")
python
def build(self, format='qcow2', path='/tmp'): ''' Build an image using Kiwi. :param format: :param path: :return: ''' if kiwi is None: msg = 'Unable to build the image due to the missing dependencies: Kiwi module is not available.' log.error(msg) raise CommandExecutionError(msg) raise CommandExecutionError("Build is not yet implemented")
[ "def", "build", "(", "self", ",", "format", "=", "'qcow2'", ",", "path", "=", "'/tmp'", ")", ":", "if", "kiwi", "is", "None", ":", "msg", "=", "'Unable to build the image due to the missing dependencies: Kiwi module is not available.'", "log", ".", "error", "(", "...
Build an image using Kiwi. :param format: :param path: :return:
[ "Build", "an", "image", "using", "Kiwi", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/collector.py#L459-L472
train
saltstack/salt
salt/states/xml.py
value_present
def value_present(name, xpath, value, **kwargs): ''' .. versionadded:: Neon Manages a given XML file name : string The location of the XML file to manage, as an absolute path. xpath : string xpath location to manage value : string value to ensure present .. code-block:: yaml ensure_value_true: xml.value_present: - name: /tmp/test.xml - xpath: .//playwright[@id='1'] - value: William Shakespeare ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if 'test' not in kwargs: kwargs['test'] = __opts__.get('test', False) current_value = __salt__['xml.get_value'](name, xpath) if not current_value: ret['result'] = False ret['comment'] = 'xpath query {0} not found in {1}'.format(xpath, name) return ret if current_value != value: if kwargs['test']: ret['result'] = None ret['comment'] = '{0} will be updated'.format(name) ret['changes'] = {name: {'old': current_value, 'new': value}} else: results = __salt__['xml.set_value'](name, xpath, value) ret['result'] = results ret['comment'] = '{0} updated'.format(name) ret['changes'] = {name: {'old': current_value, 'new': value}} else: ret['comment'] = '{0} is already present'.format(value) return ret
python
def value_present(name, xpath, value, **kwargs): ''' .. versionadded:: Neon Manages a given XML file name : string The location of the XML file to manage, as an absolute path. xpath : string xpath location to manage value : string value to ensure present .. code-block:: yaml ensure_value_true: xml.value_present: - name: /tmp/test.xml - xpath: .//playwright[@id='1'] - value: William Shakespeare ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if 'test' not in kwargs: kwargs['test'] = __opts__.get('test', False) current_value = __salt__['xml.get_value'](name, xpath) if not current_value: ret['result'] = False ret['comment'] = 'xpath query {0} not found in {1}'.format(xpath, name) return ret if current_value != value: if kwargs['test']: ret['result'] = None ret['comment'] = '{0} will be updated'.format(name) ret['changes'] = {name: {'old': current_value, 'new': value}} else: results = __salt__['xml.set_value'](name, xpath, value) ret['result'] = results ret['comment'] = '{0} updated'.format(name) ret['changes'] = {name: {'old': current_value, 'new': value}} else: ret['comment'] = '{0} is already present'.format(value) return ret
[ "def", "value_present", "(", "name", ",", "xpath", ",", "value", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "if", "'t...
.. versionadded:: Neon Manages a given XML file name : string The location of the XML file to manage, as an absolute path. xpath : string xpath location to manage value : string value to ensure present .. code-block:: yaml ensure_value_true: xml.value_present: - name: /tmp/test.xml - xpath: .//playwright[@id='1'] - value: William Shakespeare
[ "..", "versionadded", "::", "Neon" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/xml.py#L26-L76
train
saltstack/salt
salt/states/boto_iot.py
thing_type_present
def thing_type_present(name, thingTypeName, thingTypeDescription, searchableAttributesList, region=None, key=None, keyid=None, profile=None): ''' Ensure thing type exists. .. versionadded:: 2016.11.0 name The name of the state definition thingTypeName Name of the thing type thingTypeDescription Description of the thing type searchableAttributesList List of string attributes that are searchable for the thing type region Region to connect to. key Secret key to be used. keyid Access key to be used profile A dict with region, key, keyid, or a pillar key (string) that contains a dict with region, key, and keyid ''' ret = { 'name': thingTypeName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.thing_type_exists']( thingTypeName=thingTypeName, region=region, key=key, keyid=keyid, profile=profile ) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create thing type: {0}.'.format(r['error']['message']) return ret if r.get('exists'): ret['result'] = True ret['comment'] = 'Thing type with given name {0} already exists'.format(thingTypeName) return ret if __opts__['test']: ret['comment'] = 'Thing type {0} is set to be created.'.format(thingTypeName) ret['result'] = None return ret r = __salt__['boto_iot.create_thing_type']( thingTypeName=thingTypeName, thingTypeDescription=thingTypeDescription, searchableAttributesList=searchableAttributesList, region=region, key=key, keyid=keyid, profile=profile ) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create thing type: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_iot.describe_thing_type']( thingTypeName=thingTypeName, region=region, key=key, keyid=keyid, profile=profile ) ret['changes']['old'] = {'thing_type': None} ret['changes']['new'] = _describe ret['comment'] = 'Thing Type {0} created.'.format(thingTypeName) return ret
python
def thing_type_present(name, thingTypeName, thingTypeDescription, searchableAttributesList, region=None, key=None, keyid=None, profile=None): ''' Ensure thing type exists. .. versionadded:: 2016.11.0 name The name of the state definition thingTypeName Name of the thing type thingTypeDescription Description of the thing type searchableAttributesList List of string attributes that are searchable for the thing type region Region to connect to. key Secret key to be used. keyid Access key to be used profile A dict with region, key, keyid, or a pillar key (string) that contains a dict with region, key, and keyid ''' ret = { 'name': thingTypeName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.thing_type_exists']( thingTypeName=thingTypeName, region=region, key=key, keyid=keyid, profile=profile ) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create thing type: {0}.'.format(r['error']['message']) return ret if r.get('exists'): ret['result'] = True ret['comment'] = 'Thing type with given name {0} already exists'.format(thingTypeName) return ret if __opts__['test']: ret['comment'] = 'Thing type {0} is set to be created.'.format(thingTypeName) ret['result'] = None return ret r = __salt__['boto_iot.create_thing_type']( thingTypeName=thingTypeName, thingTypeDescription=thingTypeDescription, searchableAttributesList=searchableAttributesList, region=region, key=key, keyid=keyid, profile=profile ) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create thing type: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_iot.describe_thing_type']( thingTypeName=thingTypeName, region=region, key=key, keyid=keyid, profile=profile ) ret['changes']['old'] = {'thing_type': None} ret['changes']['new'] = _describe ret['comment'] = 'Thing Type {0} created.'.format(thingTypeName) return ret
[ "def", "thing_type_present", "(", "name", ",", "thingTypeName", ",", "thingTypeDescription", ",", "searchableAttributesList", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", ...
Ensure thing type exists. .. versionadded:: 2016.11.0 name The name of the state definition thingTypeName Name of the thing type thingTypeDescription Description of the thing type searchableAttributesList List of string attributes that are searchable for the thing type region Region to connect to. key Secret key to be used. keyid Access key to be used profile A dict with region, key, keyid, or a pillar key (string) that contains a dict with region, key, and keyid
[ "Ensure", "thing", "type", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iot.py#L97-L178
train
saltstack/salt
salt/states/boto_iot.py
thing_type_absent
def thing_type_absent(name, thingTypeName, region=None, key=None, keyid=None, profile=None): ''' Ensure thing type with passed properties is absent. .. versionadded:: 2016.11.0 name The name of the state definition. thingTypeName Name of the thing type. 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': thingTypeName, 'result': True, 'comment': '', 'changes': {} } _describe = __salt__['boto_iot.describe_thing_type']( thingTypeName=thingTypeName, region=region, key=key, keyid=keyid, profile=profile ) if 'error' in _describe: ret['result'] = False ret['comment'] = 'Failed to delete thing type: {0}.'.format(_describe['error']['message']) return ret if _describe and not _describe['thing_type']: ret['comment'] = 'Thing Type {0} does not exist.'.format(thingTypeName) return ret _existing_thing_type = _describe['thing_type'] _thing_type_metadata = _existing_thing_type.get('thingTypeMetadata') _deprecated = _thing_type_metadata.get('deprecated', False) if __opts__['test']: if _deprecated: _change_desc = 'removed' else: _change_desc = 'deprecated and removed' ret['comment'] = 'Thing Type {0} is set to be {1}.'.format(thingTypeName, _change_desc) ret['result'] = None return ret # initialize a delete_wait_timer to be 5 minutes # AWS does not allow delete thing type until 5 minutes # after a thing type is marked deprecated. _delete_wait_timer = 300 if _deprecated is False: _deprecate = __salt__['boto_iot.deprecate_thing_type']( thingTypeName=thingTypeName, undoDeprecate=False, region=region, key=key, keyid=keyid, profile=profile ) if 'error' in _deprecate: ret['result'] = False ret['comment'] = 'Failed to deprecate thing type: {0}.'.format(_deprecate['error']['message']) return ret else: # grab the deprecation date string from _thing_type_metadata _deprecation_date_str = _thing_type_metadata.get('deprecationDate') if _deprecation_date_str: # see if we can wait less than 5 minutes _tz_index = _deprecation_date_str.find('+') if _tz_index != -1: _deprecation_date_str = _deprecation_date_str[:_tz_index] _deprecation_date = datetime.datetime.strptime( _deprecation_date_str, "%Y-%m-%d %H:%M:%S.%f" ) _elapsed_time_delta = datetime.datetime.utcnow() - _deprecation_date if _elapsed_time_delta.seconds >= 300: _delete_wait_timer = 0 else: _delete_wait_timer = 300 - _elapsed_time_delta.seconds # wait required 5 minutes since deprecation time if _delete_wait_timer: log.warning( 'wait for %s seconds per AWS (5 minutes after deprecation time) ' 'before we can delete iot thing type', _delete_wait_timer ) time.sleep(_delete_wait_timer) # delete thing type r = __salt__['boto_iot.delete_thing_type']( thingTypeName=thingTypeName, region=region, key=key, keyid=keyid, profile=profile ) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete thing type: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = _describe ret['changes']['new'] = {'thing_type': None} ret['comment'] = 'Thing Type {0} deleted.'.format(thingTypeName) return ret
python
def thing_type_absent(name, thingTypeName, region=None, key=None, keyid=None, profile=None): ''' Ensure thing type with passed properties is absent. .. versionadded:: 2016.11.0 name The name of the state definition. thingTypeName Name of the thing type. 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': thingTypeName, 'result': True, 'comment': '', 'changes': {} } _describe = __salt__['boto_iot.describe_thing_type']( thingTypeName=thingTypeName, region=region, key=key, keyid=keyid, profile=profile ) if 'error' in _describe: ret['result'] = False ret['comment'] = 'Failed to delete thing type: {0}.'.format(_describe['error']['message']) return ret if _describe and not _describe['thing_type']: ret['comment'] = 'Thing Type {0} does not exist.'.format(thingTypeName) return ret _existing_thing_type = _describe['thing_type'] _thing_type_metadata = _existing_thing_type.get('thingTypeMetadata') _deprecated = _thing_type_metadata.get('deprecated', False) if __opts__['test']: if _deprecated: _change_desc = 'removed' else: _change_desc = 'deprecated and removed' ret['comment'] = 'Thing Type {0} is set to be {1}.'.format(thingTypeName, _change_desc) ret['result'] = None return ret # initialize a delete_wait_timer to be 5 minutes # AWS does not allow delete thing type until 5 minutes # after a thing type is marked deprecated. _delete_wait_timer = 300 if _deprecated is False: _deprecate = __salt__['boto_iot.deprecate_thing_type']( thingTypeName=thingTypeName, undoDeprecate=False, region=region, key=key, keyid=keyid, profile=profile ) if 'error' in _deprecate: ret['result'] = False ret['comment'] = 'Failed to deprecate thing type: {0}.'.format(_deprecate['error']['message']) return ret else: # grab the deprecation date string from _thing_type_metadata _deprecation_date_str = _thing_type_metadata.get('deprecationDate') if _deprecation_date_str: # see if we can wait less than 5 minutes _tz_index = _deprecation_date_str.find('+') if _tz_index != -1: _deprecation_date_str = _deprecation_date_str[:_tz_index] _deprecation_date = datetime.datetime.strptime( _deprecation_date_str, "%Y-%m-%d %H:%M:%S.%f" ) _elapsed_time_delta = datetime.datetime.utcnow() - _deprecation_date if _elapsed_time_delta.seconds >= 300: _delete_wait_timer = 0 else: _delete_wait_timer = 300 - _elapsed_time_delta.seconds # wait required 5 minutes since deprecation time if _delete_wait_timer: log.warning( 'wait for %s seconds per AWS (5 minutes after deprecation time) ' 'before we can delete iot thing type', _delete_wait_timer ) time.sleep(_delete_wait_timer) # delete thing type r = __salt__['boto_iot.delete_thing_type']( thingTypeName=thingTypeName, region=region, key=key, keyid=keyid, profile=profile ) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete thing type: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = _describe ret['changes']['new'] = {'thing_type': None} ret['comment'] = 'Thing Type {0} deleted.'.format(thingTypeName) return ret
[ "def", "thing_type_absent", "(", "name", ",", "thingTypeName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "thingTypeName", ",", "'result'", ":",...
Ensure thing type with passed properties is absent. .. versionadded:: 2016.11.0 name The name of the state definition. thingTypeName Name of the thing type. 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", "thing", "type", "with", "passed", "properties", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iot.py#L181-L296
train
saltstack/salt
salt/states/boto_iot.py
policy_present
def policy_present(name, policyName, policyDocument, region=None, key=None, keyid=None, profile=None): ''' Ensure policy exists. name The name of the state definition policyName Name of the policy. policyDocument The JSON document that describes the policy. The length of the policyDocument must be a minimum length of 1, with a maximum length of 2048, excluding whitespace. 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': policyName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.policy_exists'](policyName=policyName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create policy: {0}.'.format(r['error']['message']) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Policy {0} is set to be created.'.format(policyName) ret['result'] = None return ret r = __salt__['boto_iot.create_policy'](policyName=policyName, policyDocument=policyDocument, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create policy: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_iot.describe_policy'](policyName, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['old'] = {'policy': None} ret['changes']['new'] = _describe ret['comment'] = 'Policy {0} created.'.format(policyName) return ret ret['comment'] = os.linesep.join([ret['comment'], 'Policy {0} is present.'.format(policyName)]) ret['changes'] = {} # policy exists, ensure config matches _describe = __salt__['boto_iot.describe_policy'](policyName=policyName, region=region, key=key, keyid=keyid, profile=profile)['policy'] if isinstance(_describe['policyDocument'], six.string_types): describeDict = salt.utils.json.loads(_describe['policyDocument']) else: describeDict = _describe['policyDocument'] if isinstance(policyDocument, six.string_types): policyDocument = salt.utils.json.loads(policyDocument) r = salt.utils.data.compare_dicts(describeDict, policyDocument) if bool(r): if __opts__['test']: msg = 'Policy {0} set to be modified.'.format(policyName) ret['comment'] = msg ret['result'] = None return ret ret['comment'] = os.linesep.join([ret['comment'], 'Policy to be modified']) policyDocument = salt.utils.json.dumps(policyDocument) r = __salt__['boto_iot.create_policy_version'](policyName=policyName, policyDocument=policyDocument, setAsDefault=True, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to update policy: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret __salt__['boto_iot.delete_policy_version'](policyName=policyName, policyVersionId=_describe['defaultVersionId'], region=region, key=key, keyid=keyid, profile=profile) ret['changes'].setdefault('new', {})['policyDocument'] = policyDocument ret['changes'].setdefault('old', {})['policyDocument'] = _describe['policyDocument'] return ret
python
def policy_present(name, policyName, policyDocument, region=None, key=None, keyid=None, profile=None): ''' Ensure policy exists. name The name of the state definition policyName Name of the policy. policyDocument The JSON document that describes the policy. The length of the policyDocument must be a minimum length of 1, with a maximum length of 2048, excluding whitespace. 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': policyName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.policy_exists'](policyName=policyName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create policy: {0}.'.format(r['error']['message']) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Policy {0} is set to be created.'.format(policyName) ret['result'] = None return ret r = __salt__['boto_iot.create_policy'](policyName=policyName, policyDocument=policyDocument, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create policy: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_iot.describe_policy'](policyName, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['old'] = {'policy': None} ret['changes']['new'] = _describe ret['comment'] = 'Policy {0} created.'.format(policyName) return ret ret['comment'] = os.linesep.join([ret['comment'], 'Policy {0} is present.'.format(policyName)]) ret['changes'] = {} # policy exists, ensure config matches _describe = __salt__['boto_iot.describe_policy'](policyName=policyName, region=region, key=key, keyid=keyid, profile=profile)['policy'] if isinstance(_describe['policyDocument'], six.string_types): describeDict = salt.utils.json.loads(_describe['policyDocument']) else: describeDict = _describe['policyDocument'] if isinstance(policyDocument, six.string_types): policyDocument = salt.utils.json.loads(policyDocument) r = salt.utils.data.compare_dicts(describeDict, policyDocument) if bool(r): if __opts__['test']: msg = 'Policy {0} set to be modified.'.format(policyName) ret['comment'] = msg ret['result'] = None return ret ret['comment'] = os.linesep.join([ret['comment'], 'Policy to be modified']) policyDocument = salt.utils.json.dumps(policyDocument) r = __salt__['boto_iot.create_policy_version'](policyName=policyName, policyDocument=policyDocument, setAsDefault=True, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to update policy: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret __salt__['boto_iot.delete_policy_version'](policyName=policyName, policyVersionId=_describe['defaultVersionId'], region=region, key=key, keyid=keyid, profile=profile) ret['changes'].setdefault('new', {})['policyDocument'] = policyDocument ret['changes'].setdefault('old', {})['policyDocument'] = _describe['policyDocument'] return ret
[ "def", "policy_present", "(", "name", ",", "policyName", ",", "policyDocument", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "policyName", ",", ...
Ensure policy exists. name The name of the state definition policyName Name of the policy. policyDocument The JSON document that describes the policy. The length of the policyDocument must be a minimum length of 1, with a maximum length of 2048, excluding whitespace. 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", "policy", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iot.py#L299-L405
train
saltstack/salt
salt/states/boto_iot.py
policy_attached
def policy_attached(name, policyName, principal, region=None, key=None, keyid=None, profile=None): ''' Ensure policy is attached to the given principal. name The name of the state definition policyName Name of the policy. principal The principal which can be a certificate ARN or a Cognito ID. 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': policyName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.list_principal_policies'](principal=principal, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to attach policy: {0}.'.format(r['error']['message']) return ret attached = False for policy in r.get('policies', []): if policy.get('policyName') == policyName: attached = True break if not attached: if __opts__['test']: ret['comment'] = 'Policy {0} is set to be attached to {1}.'.format(policyName, principal) ret['result'] = None return ret r = __salt__['boto_iot.attach_principal_policy'](policyName=policyName, principal=principal, region=region, key=key, keyid=keyid, profile=profile) if not r.get('attached'): ret['result'] = False ret['comment'] = 'Failed to attach policy: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = {'attached': False} ret['changes']['new'] = {'attached': True} ret['comment'] = 'Policy {0} attached to {1}.'.format(policyName, principal) return ret ret['comment'] = os.linesep.join([ret['comment'], 'Policy {0} is attached.'.format(policyName)]) ret['changes'] = {} return ret
python
def policy_attached(name, policyName, principal, region=None, key=None, keyid=None, profile=None): ''' Ensure policy is attached to the given principal. name The name of the state definition policyName Name of the policy. principal The principal which can be a certificate ARN or a Cognito ID. 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': policyName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.list_principal_policies'](principal=principal, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to attach policy: {0}.'.format(r['error']['message']) return ret attached = False for policy in r.get('policies', []): if policy.get('policyName') == policyName: attached = True break if not attached: if __opts__['test']: ret['comment'] = 'Policy {0} is set to be attached to {1}.'.format(policyName, principal) ret['result'] = None return ret r = __salt__['boto_iot.attach_principal_policy'](policyName=policyName, principal=principal, region=region, key=key, keyid=keyid, profile=profile) if not r.get('attached'): ret['result'] = False ret['comment'] = 'Failed to attach policy: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = {'attached': False} ret['changes']['new'] = {'attached': True} ret['comment'] = 'Policy {0} attached to {1}.'.format(policyName, principal) return ret ret['comment'] = os.linesep.join([ret['comment'], 'Policy {0} is attached.'.format(policyName)]) ret['changes'] = {} return ret
[ "def", "policy_attached", "(", "name", ",", "policyName", ",", "principal", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "policyName", ",", "'re...
Ensure policy is attached to the given principal. name The name of the state definition policyName Name of the policy. principal The principal which can be a certificate ARN or a Cognito ID. 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", "policy", "is", "attached", "to", "the", "given", "principal", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iot.py#L490-L557
train
saltstack/salt
salt/states/boto_iot.py
topic_rule_present
def topic_rule_present(name, ruleName, sql, actions, description='', ruleDisabled=False, region=None, key=None, keyid=None, profile=None): ''' Ensure topic rule exists. name The name of the state definition ruleName Name of the rule. sql The SQL statement used to query the topic. actions The actions associated with the rule. description The description of the rule. ruleDisable Specifies whether the rule is disabled. 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': ruleName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.topic_rule_exists'](ruleName=ruleName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create rule: {0}.'.format(r['error']['message']) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Rule {0} is set to be created.'.format(ruleName) ret['result'] = None return ret r = __salt__['boto_iot.create_topic_rule'](ruleName=ruleName, sql=sql, actions=actions, description=description, ruleDisabled=ruleDisabled, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create rule: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_iot.describe_topic_rule'](ruleName, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['old'] = {'rule': None} ret['changes']['new'] = _describe ret['comment'] = 'Rule {0} created.'.format(ruleName) return ret ret['comment'] = os.linesep.join([ret['comment'], 'Rule {0} is present.'.format(ruleName)]) ret['changes'] = {} # policy exists, ensure config matches _describe = __salt__['boto_iot.describe_topic_rule'](ruleName=ruleName, region=region, key=key, keyid=keyid, profile=profile)['rule'] if isinstance(actions, six.string_types): actions = salt.utils.json.loads(actions) need_update = False # cmp() function is deprecated in Python 3: use the following as a substitute for 'r'. r = (_describe['actions'] > actions) - (_describe['actions'] < actions) if bool(r): need_update = True ret['changes'].setdefault('new', {})['actions'] = actions ret['changes'].setdefault('old', {})['actions'] = _describe['actions'] for var in ('sql', 'description', 'ruleDisabled'): if _describe[var] != locals()[var]: need_update = True ret['changes'].setdefault('new', {})[var] = locals()[var] ret['changes'].setdefault('old', {})[var] = _describe[var] if need_update: if __opts__['test']: msg = 'Rule {0} set to be modified.'.format(ruleName) ret['changes'] = {} ret['comment'] = msg ret['result'] = None return ret ret['comment'] = os.linesep.join([ret['comment'], 'Rule to be modified']) r = __salt__['boto_iot.replace_topic_rule'](ruleName=ruleName, sql=sql, actions=actions, description=description, ruleDisabled=ruleDisabled, region=region, key=key, keyid=keyid, profile=profile) if not r.get('replaced'): ret['result'] = False ret['comment'] = 'Failed to update rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret
python
def topic_rule_present(name, ruleName, sql, actions, description='', ruleDisabled=False, region=None, key=None, keyid=None, profile=None): ''' Ensure topic rule exists. name The name of the state definition ruleName Name of the rule. sql The SQL statement used to query the topic. actions The actions associated with the rule. description The description of the rule. ruleDisable Specifies whether the rule is disabled. 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': ruleName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.topic_rule_exists'](ruleName=ruleName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create rule: {0}.'.format(r['error']['message']) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Rule {0} is set to be created.'.format(ruleName) ret['result'] = None return ret r = __salt__['boto_iot.create_topic_rule'](ruleName=ruleName, sql=sql, actions=actions, description=description, ruleDisabled=ruleDisabled, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create rule: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_iot.describe_topic_rule'](ruleName, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['old'] = {'rule': None} ret['changes']['new'] = _describe ret['comment'] = 'Rule {0} created.'.format(ruleName) return ret ret['comment'] = os.linesep.join([ret['comment'], 'Rule {0} is present.'.format(ruleName)]) ret['changes'] = {} # policy exists, ensure config matches _describe = __salt__['boto_iot.describe_topic_rule'](ruleName=ruleName, region=region, key=key, keyid=keyid, profile=profile)['rule'] if isinstance(actions, six.string_types): actions = salt.utils.json.loads(actions) need_update = False # cmp() function is deprecated in Python 3: use the following as a substitute for 'r'. r = (_describe['actions'] > actions) - (_describe['actions'] < actions) if bool(r): need_update = True ret['changes'].setdefault('new', {})['actions'] = actions ret['changes'].setdefault('old', {})['actions'] = _describe['actions'] for var in ('sql', 'description', 'ruleDisabled'): if _describe[var] != locals()[var]: need_update = True ret['changes'].setdefault('new', {})[var] = locals()[var] ret['changes'].setdefault('old', {})[var] = _describe[var] if need_update: if __opts__['test']: msg = 'Rule {0} set to be modified.'.format(ruleName) ret['changes'] = {} ret['comment'] = msg ret['result'] = None return ret ret['comment'] = os.linesep.join([ret['comment'], 'Rule to be modified']) r = __salt__['boto_iot.replace_topic_rule'](ruleName=ruleName, sql=sql, actions=actions, description=description, ruleDisabled=ruleDisabled, region=region, key=key, keyid=keyid, profile=profile) if not r.get('replaced'): ret['result'] = False ret['comment'] = 'Failed to update rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret
[ "def", "topic_rule_present", "(", "name", ",", "ruleName", ",", "sql", ",", "actions", ",", "description", "=", "''", ",", "ruleDisabled", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "="...
Ensure topic rule exists. name The name of the state definition ruleName Name of the rule. sql The SQL statement used to query the topic. actions The actions associated with the rule. description The description of the rule. ruleDisable Specifies whether the rule is disabled. 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", "topic", "rule", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iot.py#L631-L746
train
saltstack/salt
salt/states/boto_iot.py
topic_rule_absent
def topic_rule_absent(name, ruleName, region=None, key=None, keyid=None, profile=None): ''' Ensure topic rule with passed properties is absent. name The name of the state definition. ruleName Name of the policy. 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': ruleName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.topic_rule_exists'](ruleName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to delete rule: {0}.'.format(r['error']['message']) return ret if r and not r['exists']: ret['comment'] = 'Rule {0} does not exist.'.format(ruleName) return ret if __opts__['test']: ret['comment'] = 'Rule {0} is set to be removed.'.format(ruleName) ret['result'] = None return ret r = __salt__['boto_iot.delete_topic_rule'](ruleName, region=region, key=key, keyid=keyid, profile=profile) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete rule: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = {'rule': ruleName} ret['changes']['new'] = {'rule': None} ret['comment'] = 'Rule {0} deleted.'.format(ruleName) return ret
python
def topic_rule_absent(name, ruleName, region=None, key=None, keyid=None, profile=None): ''' Ensure topic rule with passed properties is absent. name The name of the state definition. ruleName Name of the policy. 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': ruleName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_iot.topic_rule_exists'](ruleName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to delete rule: {0}.'.format(r['error']['message']) return ret if r and not r['exists']: ret['comment'] = 'Rule {0} does not exist.'.format(ruleName) return ret if __opts__['test']: ret['comment'] = 'Rule {0} is set to be removed.'.format(ruleName) ret['result'] = None return ret r = __salt__['boto_iot.delete_topic_rule'](ruleName, region=region, key=key, keyid=keyid, profile=profile) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete rule: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = {'rule': ruleName} ret['changes']['new'] = {'rule': None} ret['comment'] = 'Rule {0} deleted.'.format(ruleName) return ret
[ "def", "topic_rule_absent", "(", "name", ",", "ruleName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "ruleName", ",", "'result'", ":", "True",...
Ensure topic rule with passed properties is absent. name The name of the state definition. ruleName Name of the policy. 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", "topic", "rule", "with", "passed", "properties", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iot.py#L749-L805
train
saltstack/salt
salt/modules/useradd.py
_quote_username
def _quote_username(name): ''' Usernames can only contain ascii chars, so make sure we return a str type ''' if not isinstance(name, six.string_types): return str(name) # future lint: disable=blacklisted-function else: return salt.utils.stringutils.to_str(name)
python
def _quote_username(name): ''' Usernames can only contain ascii chars, so make sure we return a str type ''' if not isinstance(name, six.string_types): return str(name) # future lint: disable=blacklisted-function else: return salt.utils.stringutils.to_str(name)
[ "def", "_quote_username", "(", "name", ")", ":", "if", "not", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", ":", "return", "str", "(", "name", ")", "# future lint: disable=blacklisted-function", "else", ":", "return", "salt", ".", "utils", ...
Usernames can only contain ascii chars, so make sure we return a str type
[ "Usernames", "can", "only", "contain", "ascii", "chars", "so", "make", "sure", "we", "return", "a", "str", "type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L50-L57
train
saltstack/salt
salt/modules/useradd.py
_get_gecos
def _get_gecos(name, root=None): ''' Retrieve GECOS field info and return it in dictionary form ''' if root is not None and __grains__['kernel'] != 'AIX': getpwnam = functools.partial(_getpwnam, root=root) else: getpwnam = functools.partial(pwd.getpwnam) gecos_field = salt.utils.stringutils.to_unicode( getpwnam(_quote_username(name)).pw_gecos).split(',', 4) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 5: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3]), 'other': salt.utils.data.decode(gecos_field[4])}
python
def _get_gecos(name, root=None): ''' Retrieve GECOS field info and return it in dictionary form ''' if root is not None and __grains__['kernel'] != 'AIX': getpwnam = functools.partial(_getpwnam, root=root) else: getpwnam = functools.partial(pwd.getpwnam) gecos_field = salt.utils.stringutils.to_unicode( getpwnam(_quote_username(name)).pw_gecos).split(',', 4) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 5: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3]), 'other': salt.utils.data.decode(gecos_field[4])}
[ "def", "_get_gecos", "(", "name", ",", "root", "=", "None", ")", ":", "if", "root", "is", "not", "None", "and", "__grains__", "[", "'kernel'", "]", "!=", "'AIX'", ":", "getpwnam", "=", "functools", ".", "partial", "(", "_getpwnam", ",", "root", "=", ...
Retrieve GECOS field info and return it in dictionary form
[ "Retrieve", "GECOS", "field", "info", "and", "return", "it", "in", "dictionary", "form" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L60-L81
train
saltstack/salt
salt/modules/useradd.py
_update_gecos
def _update_gecos(name, key, value, root=None): ''' Common code to change a user's GECOS information ''' if value is None: value = '' elif not isinstance(value, six.string_types): value = six.text_type(value) else: value = salt.utils.stringutils.to_unicode(value) pre_info = _get_gecos(name, root=root) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['usermod'] if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) cmd.extend(('-c', _build_gecos(gecos_data), name)) __salt__['cmd.run'](cmd, python_shell=False) return _get_gecos(name, root=root).get(key) == value
python
def _update_gecos(name, key, value, root=None): ''' Common code to change a user's GECOS information ''' if value is None: value = '' elif not isinstance(value, six.string_types): value = six.text_type(value) else: value = salt.utils.stringutils.to_unicode(value) pre_info = _get_gecos(name, root=root) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['usermod'] if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) cmd.extend(('-c', _build_gecos(gecos_data), name)) __salt__['cmd.run'](cmd, python_shell=False) return _get_gecos(name, root=root).get(key) == value
[ "def", "_update_gecos", "(", "name", ",", "key", ",", "value", ",", "root", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "''", "elif", "not", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", ...
Common code to change a user's GECOS information
[ "Common", "code", "to", "change", "a", "user", "s", "GECOS", "information" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L96-L120
train
saltstack/salt
salt/modules/useradd.py
add
def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, system=False, fullname='', roomnumber='', workphone='', homephone='', other='', createhome=True, loginclass=None, nologinit=False, root=None, usergroup=None): ''' Add a user to the minion name Username LOGIN to add uid User ID of the new account gid Name or ID of the primary group of the new account groups List of supplementary groups of the new account home Home directory of the new account shell Login shell of the new account unique If not True, the user account can have a non-unique UID system Create a system account fullname GECOS field for the full name roomnumber GECOS field for the room number workphone GECOS field for the work phone homephone GECOS field for the home phone other GECOS field for other information createhome Create the user's home directory loginclass Login class for the new account (OpenBSD) nologinit Do not add the user to the lastlog and faillog databases root Directory to chroot into usergroup Create and add the user to a new primary group of the same name CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' cmd = ['useradd'] if shell: cmd.extend(['-s', shell]) if uid not in (None, ''): cmd.extend(['-u', uid]) if gid not in (None, ''): cmd.extend(['-g', gid]) elif usergroup: cmd.append('-U') if __grains__['kernel'] != 'Linux': log.warning("'usergroup' is only supported on GNU/Linux hosts.") elif groups is not None and name in groups: defs_file = '/etc/login.defs' if __grains__['kernel'] != 'OpenBSD': try: with salt.utils.files.fopen(defs_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if 'USERGROUPS_ENAB' not in line[:15]: continue if 'yes' in line: cmd.extend([ '-g', __salt__['file.group_to_gid'](name) ]) # We found what we wanted, let's break out of the loop break except OSError: log.debug('Error reading %s', defs_file, exc_info_on_loglevel=logging.DEBUG) else: usermgmt_file = '/etc/usermgmt.conf' try: with salt.utils.files.fopen(usermgmt_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if 'group' not in line[:5]: continue cmd.extend([ '-g', line.split()[-1] ]) # We found what we wanted, let's break out of the loop break except OSError: # /etc/usermgmt.conf not present: defaults will be used pass # Setting usergroup to False adds the -N command argument. If # usergroup is None, no arguments are added to allow useradd to go # with the defaults defined for the OS. if usergroup is False: cmd.append('-N') if createhome: cmd.append('-m') elif (__grains__['kernel'] != 'NetBSD' and __grains__['kernel'] != 'OpenBSD'): cmd.append('-M') if nologinit: cmd.append('-l') if home is not None: cmd.extend(['-d', home]) if not unique and __grains__['kernel'] != 'AIX': cmd.append('-o') if (system and __grains__['kernel'] != 'NetBSD' and __grains__['kernel'] != 'OpenBSD'): cmd.append('-r') if __grains__['kernel'] == 'OpenBSD': if loginclass is not None: cmd.extend(['-L', loginclass]) cmd.append(name) if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False # At this point, the user was successfully created, so return true # regardless of the outcome of the below functions. If there is a # problem wth changing any of the user's info below, it will be raised # in a future highstate call. If anyone has a better idea on how to do # this, feel free to change it, but I didn't think it was a good idea # to return False when the user was successfully created since A) the # user does exist, and B) running useradd again would result in a # nonzero exit status and be interpreted as a False result. if groups: chgroups(name, groups, root=root) if fullname: chfullname(name, fullname, root=root) if roomnumber: chroomnumber(name, roomnumber, root=root) if workphone: chworkphone(name, workphone, root=root) if homephone: chhomephone(name, homephone, root=root) if other: chother(name, other, root=root) return True
python
def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, system=False, fullname='', roomnumber='', workphone='', homephone='', other='', createhome=True, loginclass=None, nologinit=False, root=None, usergroup=None): ''' Add a user to the minion name Username LOGIN to add uid User ID of the new account gid Name or ID of the primary group of the new account groups List of supplementary groups of the new account home Home directory of the new account shell Login shell of the new account unique If not True, the user account can have a non-unique UID system Create a system account fullname GECOS field for the full name roomnumber GECOS field for the room number workphone GECOS field for the work phone homephone GECOS field for the home phone other GECOS field for other information createhome Create the user's home directory loginclass Login class for the new account (OpenBSD) nologinit Do not add the user to the lastlog and faillog databases root Directory to chroot into usergroup Create and add the user to a new primary group of the same name CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' cmd = ['useradd'] if shell: cmd.extend(['-s', shell]) if uid not in (None, ''): cmd.extend(['-u', uid]) if gid not in (None, ''): cmd.extend(['-g', gid]) elif usergroup: cmd.append('-U') if __grains__['kernel'] != 'Linux': log.warning("'usergroup' is only supported on GNU/Linux hosts.") elif groups is not None and name in groups: defs_file = '/etc/login.defs' if __grains__['kernel'] != 'OpenBSD': try: with salt.utils.files.fopen(defs_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if 'USERGROUPS_ENAB' not in line[:15]: continue if 'yes' in line: cmd.extend([ '-g', __salt__['file.group_to_gid'](name) ]) # We found what we wanted, let's break out of the loop break except OSError: log.debug('Error reading %s', defs_file, exc_info_on_loglevel=logging.DEBUG) else: usermgmt_file = '/etc/usermgmt.conf' try: with salt.utils.files.fopen(usermgmt_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if 'group' not in line[:5]: continue cmd.extend([ '-g', line.split()[-1] ]) # We found what we wanted, let's break out of the loop break except OSError: # /etc/usermgmt.conf not present: defaults will be used pass # Setting usergroup to False adds the -N command argument. If # usergroup is None, no arguments are added to allow useradd to go # with the defaults defined for the OS. if usergroup is False: cmd.append('-N') if createhome: cmd.append('-m') elif (__grains__['kernel'] != 'NetBSD' and __grains__['kernel'] != 'OpenBSD'): cmd.append('-M') if nologinit: cmd.append('-l') if home is not None: cmd.extend(['-d', home]) if not unique and __grains__['kernel'] != 'AIX': cmd.append('-o') if (system and __grains__['kernel'] != 'NetBSD' and __grains__['kernel'] != 'OpenBSD'): cmd.append('-r') if __grains__['kernel'] == 'OpenBSD': if loginclass is not None: cmd.extend(['-L', loginclass]) cmd.append(name) if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False # At this point, the user was successfully created, so return true # regardless of the outcome of the below functions. If there is a # problem wth changing any of the user's info below, it will be raised # in a future highstate call. If anyone has a better idea on how to do # this, feel free to change it, but I didn't think it was a good idea # to return False when the user was successfully created since A) the # user does exist, and B) running useradd again would result in a # nonzero exit status and be interpreted as a False result. if groups: chgroups(name, groups, root=root) if fullname: chfullname(name, fullname, root=root) if roomnumber: chroomnumber(name, roomnumber, root=root) if workphone: chworkphone(name, workphone, root=root) if homephone: chhomephone(name, homephone, root=root) if other: chother(name, other, root=root) return True
[ "def", "add", "(", "name", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "groups", "=", "None", ",", "home", "=", "None", ",", "shell", "=", "None", ",", "unique", "=", "True", ",", "system", "=", "False", ",", "fullname", "=", "''", "...
Add a user to the minion name Username LOGIN to add uid User ID of the new account gid Name or ID of the primary group of the new account groups List of supplementary groups of the new account home Home directory of the new account shell Login shell of the new account unique If not True, the user account can have a non-unique UID system Create a system account fullname GECOS field for the full name roomnumber GECOS field for the room number workphone GECOS field for the work phone homephone GECOS field for the home phone other GECOS field for other information createhome Create the user's home directory loginclass Login class for the new account (OpenBSD) nologinit Do not add the user to the lastlog and faillog databases root Directory to chroot into usergroup Create and add the user to a new primary group of the same name CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell>
[ "Add", "a", "user", "to", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L123-L313
train
saltstack/salt
salt/modules/useradd.py
delete
def delete(name, remove=False, force=False, root=None): ''' Remove a user from the minion name Username to delete remove Remove home directory and mail spool force Force some actions that would fail otherwise root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' cmd = ['userdel'] if remove: cmd.append('-r') if force and __grains__['kernel'] != 'OpenBSD' and __grains__['kernel'] != 'AIX': cmd.append('-f') cmd.append(name) if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] == 0: # Command executed with no errors return True if ret['retcode'] == 12: # There's a known bug in Debian based distributions, at least, that # makes the command exit with 12, see: # https://bugs.launchpad.net/ubuntu/+source/shadow/+bug/1023509 if __grains__['os_family'] not in ('Debian',): return False if 'var/mail' in ret['stderr'] or 'var/spool/mail' in ret['stderr']: # We've hit the bug, let's log it and not fail log.debug( 'While the userdel exited with code 12, this is a known bug on ' 'debian based distributions. See http://goo.gl/HH3FzT' ) return True return False
python
def delete(name, remove=False, force=False, root=None): ''' Remove a user from the minion name Username to delete remove Remove home directory and mail spool force Force some actions that would fail otherwise root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' cmd = ['userdel'] if remove: cmd.append('-r') if force and __grains__['kernel'] != 'OpenBSD' and __grains__['kernel'] != 'AIX': cmd.append('-f') cmd.append(name) if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] == 0: # Command executed with no errors return True if ret['retcode'] == 12: # There's a known bug in Debian based distributions, at least, that # makes the command exit with 12, see: # https://bugs.launchpad.net/ubuntu/+source/shadow/+bug/1023509 if __grains__['os_family'] not in ('Debian',): return False if 'var/mail' in ret['stderr'] or 'var/spool/mail' in ret['stderr']: # We've hit the bug, let's log it and not fail log.debug( 'While the userdel exited with code 12, this is a known bug on ' 'debian based distributions. See http://goo.gl/HH3FzT' ) return True return False
[ "def", "delete", "(", "name", ",", "remove", "=", "False", ",", "force", "=", "False", ",", "root", "=", "None", ")", ":", "cmd", "=", "[", "'userdel'", "]", "if", "remove", ":", "cmd", ".", "append", "(", "'-r'", ")", "if", "force", "and", "__gr...
Remove a user from the minion name Username to delete remove Remove home directory and mail spool force Force some actions that would fail otherwise root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True
[ "Remove", "a", "user", "from", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L316-L372
train
saltstack/salt
salt/modules/useradd.py
getent
def getent(refresh=False, root=None): ''' Return the list of all info for all users refresh Force a refresh of user information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] if root is not None and __grains__['kernel'] != 'AIX': getpwall = functools.partial(_getpwall, root=root) else: getpwall = functools.partial(pwd.getpwall) for data in getpwall(): ret.append(_format_info(data)) __context__['user.getent'] = ret return ret
python
def getent(refresh=False, root=None): ''' Return the list of all info for all users refresh Force a refresh of user information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] if root is not None and __grains__['kernel'] != 'AIX': getpwall = functools.partial(_getpwall, root=root) else: getpwall = functools.partial(pwd.getpwall) for data in getpwall(): ret.append(_format_info(data)) __context__['user.getent'] = ret return ret
[ "def", "getent", "(", "refresh", "=", "False", ",", "root", "=", "None", ")", ":", "if", "'user.getent'", "in", "__context__", "and", "not", "refresh", ":", "return", "__context__", "[", "'user.getent'", "]", "ret", "=", "[", "]", "if", "root", "is", "...
Return the list of all info for all users refresh Force a refresh of user information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.getent
[ "Return", "the", "list", "of", "all", "info", "for", "all", "users" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L375-L403
train
saltstack/salt
salt/modules/useradd.py
_chattrib
def _chattrib(name, key, value, param, persist=False, root=None): ''' Change an attribute for a named user ''' pre_info = info(name, root=root) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if value == pre_info[key]: return True cmd = ['usermod'] if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) if persist and __grains__['kernel'] != 'OpenBSD': cmd.append('-m') cmd.extend((param, value, name)) __salt__['cmd.run'](cmd, python_shell=False) return info(name, root=root).get(key) == value
python
def _chattrib(name, key, value, param, persist=False, root=None): ''' Change an attribute for a named user ''' pre_info = info(name, root=root) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if value == pre_info[key]: return True cmd = ['usermod'] if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) if persist and __grains__['kernel'] != 'OpenBSD': cmd.append('-m') cmd.extend((param, value, name)) __salt__['cmd.run'](cmd, python_shell=False) return info(name, root=root).get(key) == value
[ "def", "_chattrib", "(", "name", ",", "key", ",", "value", ",", "param", ",", "persist", "=", "False", ",", "root", "=", "None", ")", ":", "pre_info", "=", "info", "(", "name", ",", "root", "=", "root", ")", "if", "not", "pre_info", ":", "raise", ...
Change an attribute for a named user
[ "Change", "an", "attribute", "for", "a", "named", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L406-L428
train
saltstack/salt
salt/modules/useradd.py
chhome
def chhome(name, home, persist=False, root=None): ''' Change the home directory of the user, pass True for persist to move files to the new home directory if the old home directory exist. name User to modify home New home directory for the user account presist Move contents of the home directory to the new location root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' return _chattrib(name, 'home', home, '-d', persist=persist, root=root)
python
def chhome(name, home, persist=False, root=None): ''' Change the home directory of the user, pass True for persist to move files to the new home directory if the old home directory exist. name User to modify home New home directory for the user account presist Move contents of the home directory to the new location root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' return _chattrib(name, 'home', home, '-d', persist=persist, root=root)
[ "def", "chhome", "(", "name", ",", "home", ",", "persist", "=", "False", ",", "root", "=", "None", ")", ":", "return", "_chattrib", "(", "name", ",", "'home'", ",", "home", ",", "'-d'", ",", "persist", "=", "persist", ",", "root", "=", "root", ")" ...
Change the home directory of the user, pass True for persist to move files to the new home directory if the old home directory exist. name User to modify home New home directory for the user account presist Move contents of the home directory to the new location root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True
[ "Change", "the", "home", "directory", "of", "the", "user", "pass", "True", "for", "persist", "to", "move", "files", "to", "the", "new", "home", "directory", "if", "the", "old", "home", "directory", "exist", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L497-L520
train
saltstack/salt
salt/modules/useradd.py
chgroups
def chgroups(name, groups, append=False, root=None): ''' Change the groups to which this user belongs name User to modify groups Groups to set for the user append : False If ``True``, append the specified group(s). Otherwise, this function will replace the user's groups with the specified group(s). root Directory to chroot into CLI Examples: .. code-block:: bash salt '*' user.chgroups foo wheel,root salt '*' user.chgroups foo wheel,root append=True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True cmd = ['usermod'] if __grains__['kernel'] != 'OpenBSD': if append and __grains__['kernel'] != 'AIX': cmd.append('-a') cmd.append('-G') else: if append: cmd.append('-G') else: cmd.append('-S') if append and __grains__['kernel'] == 'AIX': cmd.extend([','.join(ugrps) + ',' + ','.join(groups), name]) else: cmd.extend([','.join(groups), name]) if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) result = __salt__['cmd.run_all'](cmd, python_shell=False) # try to fallback on gpasswd to add user to localgroups # for old lib-pamldap support if __grains__['kernel'] != 'OpenBSD' and __grains__['kernel'] != 'AIX': if result['retcode'] != 0 and 'not found in' in result['stderr']: ret = True for group in groups: cmd = ['gpasswd', '-a', name, group] if __salt__['cmd.retcode'](cmd, python_shell=False) != 0: ret = False return ret return result['retcode'] == 0
python
def chgroups(name, groups, append=False, root=None): ''' Change the groups to which this user belongs name User to modify groups Groups to set for the user append : False If ``True``, append the specified group(s). Otherwise, this function will replace the user's groups with the specified group(s). root Directory to chroot into CLI Examples: .. code-block:: bash salt '*' user.chgroups foo wheel,root salt '*' user.chgroups foo wheel,root append=True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True cmd = ['usermod'] if __grains__['kernel'] != 'OpenBSD': if append and __grains__['kernel'] != 'AIX': cmd.append('-a') cmd.append('-G') else: if append: cmd.append('-G') else: cmd.append('-S') if append and __grains__['kernel'] == 'AIX': cmd.extend([','.join(ugrps) + ',' + ','.join(groups), name]) else: cmd.extend([','.join(groups), name]) if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) result = __salt__['cmd.run_all'](cmd, python_shell=False) # try to fallback on gpasswd to add user to localgroups # for old lib-pamldap support if __grains__['kernel'] != 'OpenBSD' and __grains__['kernel'] != 'AIX': if result['retcode'] != 0 and 'not found in' in result['stderr']: ret = True for group in groups: cmd = ['gpasswd', '-a', name, group] if __salt__['cmd.retcode'](cmd, python_shell=False) != 0: ret = False return ret return result['retcode'] == 0
[ "def", "chgroups", "(", "name", ",", "groups", ",", "append", "=", "False", ",", "root", "=", "None", ")", ":", "if", "isinstance", "(", "groups", ",", "six", ".", "string_types", ")", ":", "groups", "=", "groups", ".", "split", "(", "','", ")", "u...
Change the groups to which this user belongs name User to modify groups Groups to set for the user append : False If ``True``, append the specified group(s). Otherwise, this function will replace the user's groups with the specified group(s). root Directory to chroot into CLI Examples: .. code-block:: bash salt '*' user.chgroups foo wheel,root salt '*' user.chgroups foo wheel,root append=True
[ "Change", "the", "groups", "to", "which", "this", "user", "belongs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L523-L583
train
saltstack/salt
salt/modules/useradd.py
chloginclass
def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user name User to modify loginclass Login class for the new account root Directory to chroot into .. note:: This function only applies to OpenBSD systems. CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if __grains__['kernel'] != 'OpenBSD': return False if loginclass == get_loginclass(name): return True cmd = ['usermod', '-L', loginclass, name] if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass
python
def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user name User to modify loginclass Login class for the new account root Directory to chroot into .. note:: This function only applies to OpenBSD systems. CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if __grains__['kernel'] != 'OpenBSD': return False if loginclass == get_loginclass(name): return True cmd = ['usermod', '-L', loginclass, name] if root is not None and __grains__['kernel'] != 'AIX': cmd.extend(('-R', root)) __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass
[ "def", "chloginclass", "(", "name", ",", "loginclass", ",", "root", "=", "None", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "!=", "'OpenBSD'", ":", "return", "False", "if", "loginclass", "==", "get_loginclass", "(", "name", ")", ":", "return", "...
Change the default login class of the user name User to modify loginclass Login class for the new account root Directory to chroot into .. note:: This function only applies to OpenBSD systems. CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff
[ "Change", "the", "default", "login", "class", "of", "the", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L687-L721
train
saltstack/salt
salt/modules/useradd.py
info
def info(name, root=None): ''' Return user information name User to get the information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.info root ''' # If root is provided, we use a less portable solution that # depends on analyzing /etc/passwd manually. Of course we cannot # find users from NIS nor LDAP, but in those cases do not makes # sense to provide a root parameter. # # Please, note that if the non-root /etc/passwd file is long the # iteration can be slow. if root is not None and __grains__['kernel'] != 'AIX': getpwnam = functools.partial(_getpwnam, root=root) else: getpwnam = functools.partial(pwd.getpwnam) try: data = getpwnam(_quote_username(name)) except KeyError: return {} else: return _format_info(data)
python
def info(name, root=None): ''' Return user information name User to get the information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.info root ''' # If root is provided, we use a less portable solution that # depends on analyzing /etc/passwd manually. Of course we cannot # find users from NIS nor LDAP, but in those cases do not makes # sense to provide a root parameter. # # Please, note that if the non-root /etc/passwd file is long the # iteration can be slow. if root is not None and __grains__['kernel'] != 'AIX': getpwnam = functools.partial(_getpwnam, root=root) else: getpwnam = functools.partial(pwd.getpwnam) try: data = getpwnam(_quote_username(name)) except KeyError: return {} else: return _format_info(data)
[ "def", "info", "(", "name", ",", "root", "=", "None", ")", ":", "# If root is provided, we use a less portable solution that", "# depends on analyzing /etc/passwd manually. Of course we cannot", "# find users from NIS nor LDAP, but in those cases do not makes", "# sense to provide a root p...
Return user information name User to get the information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.info root
[ "Return", "user", "information" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L724-L757
train
saltstack/salt
salt/modules/useradd.py
get_loginclass
def get_loginclass(name): ''' Get the login class of the user name User to get the information .. note:: This function only applies to OpenBSD systems. CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' if __grains__['kernel'] != 'OpenBSD': return False userinfo = __salt__['cmd.run_stdout']( ['userinfo', name], python_shell=False) for line in userinfo.splitlines(): if line.startswith('class'): try: ret = line.split(None, 1)[1] break except (ValueError, IndexError): continue else: ret = '' return ret
python
def get_loginclass(name): ''' Get the login class of the user name User to get the information .. note:: This function only applies to OpenBSD systems. CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' if __grains__['kernel'] != 'OpenBSD': return False userinfo = __salt__['cmd.run_stdout']( ['userinfo', name], python_shell=False) for line in userinfo.splitlines(): if line.startswith('class'): try: ret = line.split(None, 1)[1] break except (ValueError, IndexError): continue else: ret = '' return ret
[ "def", "get_loginclass", "(", "name", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "!=", "'OpenBSD'", ":", "return", "False", "userinfo", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "[", "'userinfo'", ",", "name", "]", ",", "python_shell", "...
Get the login class of the user name User to get the information .. note:: This function only applies to OpenBSD systems. CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo
[ "Get", "the", "login", "class", "of", "the", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L760-L790
train